diff --git a/.claude/settings.json b/.claude/settings.json index 4be5930d..24efbd66 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -39,5 +39,16 @@ ] } ] + }, + "extraKnownMarketplaces": { + "claude-harness": { + "source": { + "source": "git", + "url": "https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness.git" + } + } + }, + "enabledPlugins": { + "harness@claude-harness": true } } diff --git a/.github/workflows/ci-quality-gates.yml b/.github/workflows/ci-quality-gates.yml index d26c661c..830d59cb 100644 --- a/.github/workflows/ci-quality-gates.yml +++ b/.github/workflows/ci-quality-gates.yml @@ -62,70 +62,9 @@ jobs: - name: Refuse a top-level folder outside the allow list run: python3 scripts/check-repo-layout.py - optional-platforms: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Verify the optional gRPC platform build - working-directory: src - run: ./gradlew -p platforms/optional-build ci --stacktrace - # The optional build's own lane-reachability check: the main build's cannot see these lanes - # (review 2026-11-03 RR-06-03). - - name: Require every optional-platform strict lane to be in an executed stage - working-directory: src - run: ./gradlew -p platforms/optional-build :verifyStrictLaneStages --dry-run --stacktrace - - # gRPC schema policy (owner decision 18). protoc compiles src/platforms/grpc/grpc-contract inside - # the optional-platforms build above; lint and breaking-change policy belong to Buf, configured by - # buf.yaml next to the schema. Buf is a native binary rather than a Maven artifact, so it runs here - # and not inside Gradle — and nothing in the repository re-implements its rules. - grpc-proto-buf: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - with: - # buf breaking reads the baseline schema from Git history. - fetch-depth: 0 - - uses: bufbuild/buf-action@85aebf73123b5c15fd5528aaecbf9129cddf7fa7 # bufbuild/buf-action@v1.6.0 - with: - version: 1.73.0 - setup_only: true - - name: Lint the gRPC schema - working-directory: src/platforms/grpc/grpc-contract - run: buf lint - - name: Refuse a breaking change to the gRPC schema - working-directory: src/platforms/grpc/grpc-contract - env: - # Pull request: the target branch. Push: the commit this push replaced. - BASELINE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || github.event.before }} - run: | - set -euo pipefail - baseline_commit="$(git rev-parse --verify --quiet "${BASELINE}^{commit}" || true)" - # The module moved from src/grpc to src/platforms/grpc on 2026-11-07. A baseline from - # before the move holds it at the old path, and comparing against that path keeps the - # breaking check running across the move instead of skipping it once. - baseline_dir="" - if [[ -n "${baseline_commit}" ]]; then - for candidate in src/platforms/grpc/grpc-contract src/grpc/grpc-contract; do - if git cat-file -e "${baseline_commit}:${candidate}/buf.yaml" 2>/dev/null; then - baseline_dir="${candidate}" - break - fi - done - fi - if [[ -z "${baseline_dir}" ]]; then - # The first change that introduces the module has nothing to be compatible with. - echo "::notice::grpc-proto-buf: baseline ${BASELINE} has no grpc-contract/buf.yaml; breaking check skipped." - exit 0 - fi - buf breaking --against "../../../../.git#ref=${baseline_commit},subdir=${baseline_dir}" - release-gate: needs: - quality-gates - - optional-platforms - - grpc-proto-buf if: always() runs-on: ubuntu-latest permissions: @@ -134,14 +73,10 @@ jobs: - name: Require every current blocking job to succeed env: QUALITY_RESULT: ${{ needs.quality-gates.result }} - OPTIONAL_PLATFORMS_RESULT: ${{ needs.optional-platforms.result }} - GRPC_PROTO_BUF_RESULT: ${{ needs.grpc-proto-buf.result }} run: | set -euo pipefail for result in \ - "${QUALITY_RESULT}" \ - "${OPTIONAL_PLATFORMS_RESULT}" \ - "${GRPC_PROTO_BUF_RESULT}"; do + "${QUALITY_RESULT}"; do if [[ "${result}" != "success" ]]; then echo "::error::release-gate: required job result was ${result}" exit 1 diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index 4c676633..6f8d8366 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -202,12 +202,6 @@ jobs: - name: Run every performance-category strict lane working-directory: src run: ./gradlew :performanceCheck --continue --stacktrace - # The optional gRPC build's performance lanes (grpcPerformanceTest). A separate build, so a - # separate command; its own verifyStrictLaneStages counts this line (review 2026-11-03 RR-06-03). - - name: Run every optional-platform performance-category strict lane - if: always() - working-directory: src - run: ./gradlew -p platforms/optional-build performanceCheck --continue --stacktrace - name: Publish the performance lane reports if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 @@ -230,35 +224,6 @@ jobs: working-directory: src run: ./gradlew :adapter:outbound:httpclient:test -Phttp3.tests.enabled=true --stacktrace - # The optional gRPC platform build declares one strict INTEGRATION lane — - # `grpc-operation-ledger-jpa:integrationTest`, which certifies the atomic - # `INSERT ... ON CONFLICT DO NOTHING` claim that durable mutation idempotency rests on against a - # real PostgreSQL. It was registered in Gradle, listed in `strictTestLanes`, and invoked by - # nothing: `-p platforms/optional-build ci` reaches `checkAll`, `qualityCheck` and the dependency - # verifier, none of which runs a lane whose category is INTEGRATION, and release.yml's gRPC gate - # names only the three grpc-testkit lanes. - # - # Stage 2 rather than stage 1 for the same reason as every other job in this file: the lane starts - # a Testcontainers PostgreSQL, and the pull-request budget is minutes for the whole gate. - grpc-optional-platform-integration: - runs-on: ubuntu-latest - timeout-minutes: 45 - env: - TESTCONTAINERS_REUSE_ENABLE: "false" - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Certify the gRPC operation ledger against real PostgreSQL - working-directory: src - run: ./gradlew -p platforms/optional-build integrationCheck --stacktrace - - name: Publish the optional-platform lane reports - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 - with: - name: grpc-optional-platform-integration-reports - path: src/platforms/grpc*/**/build/reports/tests/ - if-no-files-found: warn - # Dynamic half of the compose-profile contract. Every blocking lane the matrix declares runs on # 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8a0593e4..da695084 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -108,49 +108,6 @@ jobs: path: src/adapter/inbound/websocket/build/reports/tests/ if-no-files-found: error - # 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 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. - # - # Release rather than nightly, for the same reason web-stable-release-gate is: these lanes need no - # container and no fixed cadence — grpcNettyContractTest opens an ephemeral socket, not a broker — - # so the guard is worth asserting once per tag and is not worth a runner every night. - # - # The optional build's `releaseCheck` is those hermetic lanes, so a lane added there is here - # without a workflow edit. grpcPerformanceTest is deliberately absent: a measurement is not release - # evidence on a shared runner. It runs in integration-main.yml's performance-check job (the - # optional build's `performanceCheck`). - grpc-stable-release-gate: - runs-on: ubuntu-latest - timeout-minutes: 45 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Run the gRPC Stable certification lanes - working-directory: src - run: ./gradlew -p platforms/optional-build releaseCheck --stacktrace - # The operation ledger's real-PostgreSQL lane ran only on main and nightly - # (integration-main.yml), so a tag could be cut from a main whose ledger lane was red. It needs - # Docker, which a release runner has (review 2026-11-01 03-12). - - name: Certify the gRPC operation ledger against real PostgreSQL - working-directory: src - env: - TESTCONTAINERS_REUSE_ENABLE: "false" - run: ./gradlew -p platforms/optional-build integrationCheck --stacktrace - - name: Publish the gRPC release evidence - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 - with: - name: grpc-release-evidence - path: | - src/platforms/grpc/grpc-testkit/build/reports/tests/ - src/platforms/grpc/grpc-operation-ledger-jpa/build/reports/tests/ - if-no-files-found: warn - # Each gate runs as its own single-line `./gradlew ` step so that a failure names the gate # rather than a folded command. The architecture dependency gate that used to end this list is now # architecture-and-surface above; it was the fourth copy of the same invocation. @@ -344,7 +301,6 @@ jobs: - architecture-and-surface - web-stable-release-gate - websocket-stable-release-gate - - grpc-stable-release-gate - httpclient-release-gate - httpclient-documentation - jpa-release-promotion diff --git a/CLAUDE.md b/CLAUDE.md index f30f0dfc..dcecaf6b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,6 +3,7 @@ ## Claude Code에서만 - 권한과 훅은 `.claude/settings.json`이다: 편집 직후 Java 한 파일 포맷·레이어 의존 알림·문서 검사, 턴 끝 desktop 검증 알림, 적용된 migration 편집 차단, 실제 `.env` 읽기 차단. 훅마다 하는 일과 시험은 `scripts/hooks/README.md`다. +- 공통 훅·스킬(되돌릴 수 없는 명령 차단, 비밀 값 알림, 장부, `estimate`·`retro`·`techdebt`)은 하네스 플러그인 `harness@claude-harness`다(같은 settings가 켠다). 비대화형(`claude -p`)은 설치하지 않으니 claude-harness README의 `--scope project` 두 명령을 한 번 돌린다. - 경로별 규칙(테스트·설정·Docker·문서)은 `.claude/rules/`에 있다. 그 경로의 파일을 열 때 읽힌다. - 스킬은 `.claude/skills/`다: `new-feature`(새 기능), `desktop-gates`(Gradle·Docker를 desktop에서). 발동 조건이 설명에 있어 모델이 부른다. - 서브에이전트는 `.claude/agents/`다: `arch-reviewer`(구조 리뷰), `verify-api`(desktop에서 앱 띄워 확인), `code-simplifier`(단순화 제안). 모두 결과만 돌려주고 파일을 고치지 않는다. diff --git a/README.md b/README.md index 4a2bd33c..1f587291 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ ca-skeleton은 Java 21과 Spring Boot로 만든 Gradle 멀티모듈 백엔드 | `adapter/outbound/` | port 뒤의 구현: 영속성(JPA·MongoDB), Redis, 메시징, 알림, 객체 저장소, 파일 서버, HTTP client, identifier, 공용 기반(support) | `support`·`identifier`만 들어간다 | | `composition/` | 조립만 하는 leaf: 서비스 런타임 배선, outbox relay, 멱등성 executor, durable operation, 알림·파일 서버 플랫폼 | `service-runtime`·`outbox-relay`·`idempotency`·`durable-operation`이 들어간다. 뒤의 셋은 필요한 port가 생기기 전에는 아무것도 만들지 않는다 | | `app-bootstrap/` | Spring Boot 진입점과 조립 루트(composition root, 모든 모듈을 엮는 곳) | 들어간다 | -| `platforms/` | 들여온 제품: `messaging`(메시징 플랫폼), `grpc`·`grpc-advanced`(gRPC 라이브러리, 다른 빌드 `optional-build`) | 들어가지 않는다. adapter를 거쳐서만 닿는다 | +| `platforms/` | 들여온 제품: `messaging`(메시징 플랫폼). gRPC 플랫폼 라이브러리는 2026-11-08에 별도 repo `grpc-library`로 옮겼다([관련 저장소](docs/work/reference/related-repos.md)) | 들어가지 않는다. adapter를 거쳐서만 닿는다 | | `build-logic/`, `config/`, `gradle/` | 빌드 규칙(convention plugin), 빌드 전체 도구 설정과 registry, wrapper와 버전 카탈로그 | 빌드 도구 | 의존은 항상 바깥에서 안으로 흐른다. adapter가 core의 port에 의존하고, core는 adapter를 모른다. @@ -122,7 +122,7 @@ cd src 3. `CaSkeletonApplication`을 새 애플리케이션 이름으로 바꾼다. 4. 새 업무 기능은 `scripts/new-feature.sh `으로 만들고 [docs/manual/README.md](docs/manual/README.md) 순서대로 채운다. 모듈 이름과 경계는 그대로 둔다. 5. 쓰는 capability의 `runtimeOnly` 줄만 켠다. 켜지 않은 capability leaf는 산출물에 들어가지 않으니 지우지 않아도 된다. -6. gRPC 플랫폼을 쓰면 proto 조직 이름 `caskeleton`도 바꾼다. `src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/` 디렉터리와 각 `.proto`의 `package`·`java_package`다. `buf lint`로 확인한다. +6. 라이브러리 패키지 `dev.cakit.*`은 바꾸지 않는다. 별도 repo에서 받는 라이브러리의 패키지이고, 2번이 바꾸는 `dev.caskeleton`과 이름이 겹치지 않게 정했다. 라이브러리 목록은 [관련 저장소](docs/work/reference/related-repos.md)다. 7. Docker 이미지 이름과 애플리케이션 이름(`spring.application.name`)을 새 서비스 기준으로 바꾼다. 8. `src/.env.example`, `src/.env.local.example`, `application.yml`의 예시 값을 새 서비스의 실행 요구에 맞춘다. 운영 모듈에는 그 서비스의 entity, repository port, use case, adapter만 더한다. 9. README와 운영 문서를 새 서비스 설명으로 고친다. diff --git a/docs/README.md b/docs/README.md index f399bcfd..7b84d7f8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -35,7 +35,6 @@ | `architecture/` | 공개 API 표면 스냅숏(`*-api-surface.txt`). API surface 검사가 대조한다 | | `security/` | 기본 공개 경로 스냅숏. `verifyPublicPathSnapshot`이 대조한다 | | `observability/` | 구조화 로그 필드 사전 | -| `compatibility/` | gRPC 플랫폼 지원 매트릭스(무엇에 대해 인증했고 무엇은 지켜보기만 하나) | ### 영역 운영 문서 diff --git a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md index 540cbaa0..7f537ea9 100644 --- a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md +++ b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md @@ -4,7 +4,7 @@ - 상태: 채택 - 작성일: 2026-08-30 - 요약: gRPC 플랫폼을 adapter leaf 하나가 아니라 registry에 등록한 family로 낸다는 결정이다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 # ADR-GRPC-001: gRPC 플랫폼은 adapter leaf 하나가 아니라 등록된 family로 싣는다 diff --git a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md index b0a745c8..a3f34e1a 100644 --- a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md +++ b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md @@ -4,7 +4,7 @@ - 상태: 대체됨 - 작성일: 2026-08-30 - 요약: protoc와 Buf CLI 없이 스키마를 관리하려던 결정이다. 2026-09-28 Gradle protobuf plugin과 buf로 바뀌었다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 - 대체됨: `docs/capability-status.md` diff --git a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md index 2caa19dd..f912f7ee 100644 --- a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md +++ b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md @@ -4,7 +4,7 @@ - 상태: 채택 - 작성일: 2026-08-30 - 요약: 전송·업무·스트림 증거를 서로 대신하지 않는 세 축으로 본다는 결정이다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 # ADR-GRPC-003: 전송·업무·stream 증거는 세 축이고, 어느 것도 다른 것을 뜻하지 않는다 diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index 9e2f827c..40c6a6c4 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -4,7 +4,7 @@ - 상태: 채택 - 작성일: 2026-08-30 - 요약: 재시도 주인은 하나이고 키가 있는 변경은 영속 원장이 필요하다는 결정이다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 # ADR-GRPC-004: 재시도 소유자는 하나이고, 키가 있는 변경에는 durable 원장이 필요하다 diff --git a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md index e6661771..aba702ae 100644 --- a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md +++ b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md @@ -4,7 +4,7 @@ - 상태: 채택 - 작성일: 2026-08-30 - 요약: 서버 스트림은 writer 하나, 제한된 큐, 추측하지 않는 resume로 다룬다는 결정이다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 # ADR-GRPC-005: stream마다 쓰는 쪽 하나, 한계 있는 queue, 짐작하기를 거절하는 resume diff --git a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md index ec3ebf71..eb61c993 100644 --- a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md +++ b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md @@ -4,7 +4,7 @@ - 상태: 채택 - 작성일: 2026-08-31 - 요약: Stable discovery는 DNS와 정적 목록이고 Kubernetes에서는 누가 부하를 나누는지 profile이 정한다는 결정이다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 # ADR-GRPC-006: Stable discovery는 DNS와 static이고, Kubernetes profile은 누가 분산하는지 이름으로 댄다 diff --git a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md index eeea17b6..9e37b29c 100644 --- a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md +++ b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md @@ -4,7 +4,7 @@ - 상태: 채택 - 작성일: 2026-08-30 - 요약: gRPC 고급 기능마다 따로 플래그·등급·승격 기준을 둔다는 결정이다. -- 현재 정본: `docs/compatibility/grpc-advanced-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-advanced-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 # ADR-GRPC-ADV-001: advanced capability마다 자기 flag, 자기 등급, 자기 승격이 있다 diff --git a/docs/capability-status.md b/docs/capability-status.md index d0e0bdb2..241afdf7 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -38,7 +38,7 @@ lanes and CI; it is not a deployment artifact. | 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` → `integration-check` (`:integrationCheck`) | | GraphQL transport | `backend.graphql.enabled` / `APP_GRAPHQL_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:graphql')`) | leaf-level | On when present; `false` also excludes Spring GraphQL's own auto-configuration, so no `/graphql` (`GraphQlCapabilityActivationTest`). `graphqlTransportQualificationTest` runs the HTTP boundary. The deployment-mode/runtime-profile rule is the module's own `GraphQlPlatformStartupValidator`. The default jar does not ship GraphQL, so a compose lane that exercises it runs the qualification jar. | | Object storage | `app.object-storage.enabled` / `APP_OBJECTSTORAGE_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it against digest-pinned MinIO. | -| 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. | +| gRPC platform | — (separate repository) | no | **no** | no | Moved out on 2026-11-08 to the `grpc-library` repository (Maven group `dev.cakit.grpc`); this repository builds and tests none of it. `adapter:inbound:grpc` uses `io.grpc` directly and is unaffected. See `docs/work/reference/related-repos.md`. | | gRPC transport (`adapter:inbound:grpc`) | `app.grpc.server.enabled` / `APP_GRPC_SERVER_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:grpc')`) | leaf-level | Own `AutoConfiguration.imports` (`GrpcServerConfig`); on when present, and the loopback plaintext listener still needs `app.grpc.server.allow-insecure-local=true` (`GrpcSafeActivationTest`, `grpcTransportQualificationTest`). | | WebSocket transport | `app.websocket.enabled` / `APP_WEBSOCKET_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:websocket')`) | — | Own `AutoConfiguration.imports` (`WebSocketConfig`), on in a servlet app when present (`WebSocketAutoConfigurationTest`); `ConditionalTransportBuildContractTest` asserts it has no default production edge. | | 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. | diff --git a/docs/compatibility/grpc-advanced-support-matrix.md b/docs/compatibility/grpc-advanced-support-matrix.md deleted file mode 100644 index bb29f12c..00000000 --- a/docs/compatibility/grpc-advanced-support-matrix.md +++ /dev/null @@ -1,55 +0,0 @@ -# gRPC advanced capability 지원 매트릭스 - -`:grpc-advanced:*`의 모든 capability, 그 등급, 그리고 등급을 올리는 데 필요한 것이다. 기본 등급의 정본은 -`GrpcAdvancedCapability.defaultGrade`다. 근거가 있는 배포는 `GrpcAdvancedFeatureFlags.withGrade`로 바꾼다. - -capability는 모두 기본으로 꺼져 있다. 스위치는 `app.grpc.advanced..enabled`다. - -## 등급 - -| 등급 | 뜰 수 있나 | 운영에 별도 승인이 필요한가 | -| --- | --- | --- | -| `ADVANCED_STABLE` | 예 | 아니요 | -| `EXPERIMENTAL` | 예 | 예 | -| `WATCH` | 아니요 | — | -| `DISABLED` | 아니요 | — | - -## capability - -| capability | 스위치 | 등급 | 증거에 필요한 실제 인프라 | -| --- | --- | --- | --- | -| Protobuf Edition 2024 | `edition-2024` | `ADVANCED_STABLE` | — | -| Protobuf Edition 2026 | `edition-2026` | `WATCH` | — | -| client streaming | `client-streaming` | `ADVANCED_STABLE` | — | -| bidirectional streaming | `bidi-streaming` | `ADVANCED_STABLE` | — | -| 수동 flow control | `manual-flow-control` | `ADVANCED_STABLE` | — | -| 읽기 전용 unary hedging | `hedging` | `EXPERIMENTAL` | — | -| 사용자 정의 name resolver | `custom-resolver` | `ADVANCED_STABLE` | — | -| 사용자 정의 load balancer | `custom-load-balancer` | `EXPERIMENTAL` | — | -| proxyless xDS | `xds` | `EXPERIMENTAL` | xDS control plane | -| gRPC-Web | `grpc-web` | `ADVANCED_STABLE` | gRPC-Web proxy | -| Servlet HTTP/2 | `servlet-compat` | `ADVANCED_STABLE`(스위치만 있다. 2026-09-25부터 Servlet 전송 코드가 없다) | Servlet 컨테이너 | -| Spring Integration bridge | `integration-bridge` | `ADVANCED_STABLE` | — | -| Reactor 어댑터 | `reactor` | `ADVANCED_STABLE` | — | -| Kotlin coroutine / Flow | `kotlin` | `ADVANCED_STABLE` | Kotlin toolchain | -| Channelz / CSDS 진단 | `channel-diagnostics` | `ADVANCED_STABLE` | — | - -## 여기서 등급이 구체적으로 뜻하는 것 - -**등급은 배포가 아니라 계약에 대한 말이다.** 모든 capability의 계약은 이 저장소에서 구현되고 시험됐다. 실제 배포에서 나온 -증거는 어느 capability에도 없고, 승격된 것도 없다. - -**capability 넷은 여기서 의미 있는 증거를 아예 낼 수 없다.** 필요한 인프라(gRPC-Web proxy, Servlet 컨테이너, xDS control -plane, Kotlin toolchain)가 없고, 인프라 없이 돈 suite는 통과해도 아무것도 세우지 않기 때문이다. - -**Kotlin이 가장 날카로운 경우다.** 이 저장소에는 Kotlin toolchain이 없으므로 그것이 생기기 전까지 Kotlin은 여기서 지원할 수 -없다. Java 쪽 coroutine 취소 bridge(`GrpcCoroutineContextBridge`)만 구현되고 시험됐다. 컴파일 lane은 없다. - -## 승격 기준 - -| 목표 | soak | 그 밖에 필요한 것 | -| --- | --- | --- | -| `ADVANCED_STABLE` | 7일 | 호환성 증거, 보안 리뷰, 장애 증거, 성능 증거, ADR, runbook, 실제 환경 시험 | -| Stable 기본값 | 30일 | 위의 모두와 의존성·보안·운영 비용 리뷰 | - -`WATCH`는 무엇보다 먼저 `EXPERIMENTAL`이 된다. 승격은 서로 독립이다. 한 capability를 올려도 다른 것의 등급은 바뀌지 않는다. diff --git a/docs/compatibility/grpc-support-matrix.md b/docs/compatibility/grpc-support-matrix.md deleted file mode 100644 index 67e9f739..00000000 --- a/docs/compatibility/grpc-support-matrix.md +++ /dev/null @@ -1,74 +0,0 @@ -# gRPC 플랫폼 지원 매트릭스 - -Stable gRPC 플랫폼(`:grpc:*`)이 무엇에 대해 인증됐고, 무엇에 대해서는 확인만 하고, 무엇은 지켜보기만 하는지다. 그 구별이 -요점이다. 「Spring Boot와 동작한다」는 누구도 행동에 옮길 수 없는 말이다. - -릴리스 gate는 `.github/workflows/release.yml`의 `grpc-stable-release-gate` job이다. 인증된 lane마다 아무것도 돌리지 않으면 -실패하는 strict test lane이다. - -> 이력: 코드 안의 `GrpcCompatibilityMatrix`/`GrpcStableReleaseGate` 짝은 지웠다(리뷰 2026-09-24 S5-lead-4). 운영 코드도 빌드 -> 코드도 그것을 부르지 않아서 아무것도 막지 않았다. - -## lane - -| lane | 등급 | 실패하면 릴리스를 막나 | -| --- | --- | --- | -| Boot가 관리하는 플랫폼(저장소의 Spring Boot BOM) | Certified | 예 | -| 명시적 `optional`을 쓰는 proto3 | Certified | 예 | -| `grpc-netty-shaded` | Certified | 예 | -| `grpc-netty`(shade하지 않음) | Compatibility | 아니요 | -| upstream gRPC Java 버전 override | Compatibility | 아니요 | -| Protobuf Edition 2024 | Watch | 아니요 | -| Protobuf Edition 2026 | Watch | 아니요 | - -## 런타임 기준선 - -| | | -| --- | --- | -| Java | 21 | -| Spring Boot | 저장소 기준선, `src/gradle/libs.versions.toml`(계획은 4.1을 가정한다) | -| io.grpc | `src/gradle/libs.versions.toml`의 `grpc`. `GrpcPlatformModuleConventionPlugin`이 그 BOM을 모듈 범위로 import한다 | -| Protobuf | `src/gradle/libs.versions.toml`의 protobuf 항목(어느 leaf가 어느 것을 쓰는지는 그 파일의 주석이 적는다) | -| Stable 전송 | Netty(shaded) | -| Stable RPC 모양 | Unary, Server Streaming | -| Stable resolver | Static, DNS, Unix domain socket | -| Stable load balancing | `pick_first`, `round_robin` | - -## 증거 등급 - -capability는 그것을 세울 수 있는 등급의 증거로만 광고한다. `GrpcEvidenceGrade.requireCertifies`가 이것을 강제하고, -`GrpcReleaseEvidence.supports`가 맞지 않는 lane이 뒷받침하는 주장을 거부한다. - -| 등급 | lane | 세우는 것 | -| --- | --- | --- | -| `CONTRACT` | `grpcInProcessContractTest` | 어댑터, interceptor 순서, 상태 매핑, 검증, 멱등 replay, context 전파 | -| `TRANSPORT` | `grpcNettyContractTest` | HTTP/2, TLS, mTLS, metadata 한도, 메시지 한도, GOAWAY, keepalive, graceful shutdown | -| `FAULT` | `grpcFaultTest` | 연결 끊김, 완료 모름, 부분 stream, 증거 분류기 | -| `PERFORMANCE` | `grpcPerformanceTest` | 지연, stream 포화, executor 포화, drain 예산 | - -in-process 결과는 절대 전송 증거가 아니다. in-process 전송은 TLS를 협상하지 않고, HTTP/2 frame을 만들지 않고, 전송 수준 한도를 -강제하지 않는다. 그래서 거기서 통과한 suite는 전송이 아니라 어댑터를 시험한 것이다. - -## 지원하지 않는 것 - -| | 있는 곳 | -| --- | --- | -| client streaming, bidirectional streaming | `grpc-advanced` (`streaming`) | -| 수동 flow control | `grpc-advanced` (`streaming`) | -| Hedging | `grpc-advanced` (`resilience`) | -| 사용자 정의 name resolver, 사용자 정의 load balancer | `grpc-advanced` (`resilience`) | -| xDS | `grpc-advanced` (`resilience`) | -| gRPC-Web, Servlet HTTP/2, Spring Integration, Reactor, Kotlin | `grpc-advanced-compat` | -| Channelz / CSDS 진단 | `grpc-advanced` (`diagnostics`) | - -## 지금 릴리스 상태 - -릴리스하지 않았다. registry에서 모든 `:grpc:*` leaf는 `"build": "optional-grpc"`라 주 빌드 밖에 있고 어느 조립에도 들어가지 -않는다. 플랫폼은 빌드만 된다. 컴파일되고 lane이 돌지만, 배포되는 산출물 어디에도 실리지 않는다. - -릴리스 gate 입력 둘이 남아 있고, 그것이 지금부터 릴리스까지의 일이다. - -- **성능 기준선.** 성능 lane은 돌고, 절대 수치가 아니라 모양을 단언한다. 순서 있는 백분위수와 그것을 읽는 gate다. 알려진 - runner에서 기록한 기준선이 생겨야 회귀 gate가 된다. -- **schema codegen.** 이 빌드에서는 `protoc`가 돌지 않는다(ADR-GRPC-002). 그래서 descriptor 산출물과 consumer-compile fixture는 - 컴파일한 schema에서 만들어지지 않고 정책으로 다스린다. diff --git a/docs/design/2026-08-30-grpc-platform-adaptation-design.md b/docs/design/2026-08-30-grpc-platform-adaptation-design.md index 55b23bb0..2854edc0 100644 --- a/docs/design/2026-08-30-grpc-platform-adaptation-design.md +++ b/docs/design/2026-08-30-grpc-platform-adaptation-design.md @@ -4,7 +4,7 @@ - 상태: 확인 안 함 - 작성일: 2026-08-30 - 요약: 타입 안전 gRPC 실행 플랫폼 계획을 이 저장소의 구조와 게이트에 맞춘 설계다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md이고, 이 기록의 사본도 그 repo에 있다 # 타입 안전 gRPC 실행 플랫폼 — 이 저장소 규약으로의 어댑팅 설계 diff --git a/docs/history/plans/2026-08-30-grpc-platform-implementation.md b/docs/history/plans/2026-08-30-grpc-platform-implementation.md index e30b43b1..f5e26068 100644 --- a/docs/history/plans/2026-08-30-grpc-platform-implementation.md +++ b/docs/history/plans/2026-08-30-grpc-platform-implementation.md @@ -4,7 +4,7 @@ - 상태: 끝남 - 작성일: 2026-08-30 - 요약: 타입 안전 gRPC 실행 플랫폼의 실행 계획과 실행 결과다. -- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 현재 정본: 없음 — gRPC 플랫폼은 2026-11-08에 별도 repo grpc-library로 옮겼다. 지금 동작은 그 repo의 docs/compatibility/grpc-support-matrix.md다 # 타입 안전 gRPC 실행 플랫폼 — 실행 계획과 실행 결과 diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index 3d00664d..5e099d2c 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -96,14 +96,10 @@ Flyway 목록 사본을 그것이 나열한 문장에 대해 Flyway 자신과 Flyway 업그레이드가 목록에 더한 문장은 그 비교 밖이다. `LockWaitMigrationInspectorTest`가 Flyway 자신의 패턴 (`PostgreSQLParser`)을 고정하므로, 그런 업그레이드는 사본이 따라올 때까지 pull request의 `ci`를 실패시킨다. -gRPC ledger의 트리는 optional 빌드에 있어서 testkit에 의존할 수 없다. 그래서 그 `GrpcOperationLedgerMigrationLockWaitIT`가 -트리에서 읽은 V001 뒤의 모든 ledger 마이그레이션을 대신 쥔 ledger에 대고 돌리므로, 다음 마이그레이션도 실제 PostgreSQL에서 -확인된다. 그 트리를 찾고 순서를 매기는 것은 testkit 자신의 `VersionedMigrationFiles`다. ledger의 `build.gradle`이 빌드 때 -그것을 통합 테스트 소스로 복사하므로(`sharedMigrationFileSources`) 두 빌드가 한 정의를 읽는다. 그 트리의 동시 인덱스 빌드는 -트랜잭션 밖에서 돌므로 쥔 ledger로 시험할 경우가 아니다. 그런 파일은 이유와 함께 테스트의 `RUN_OUTSIDE_A_TRANSACTION`에 -넣고, 같은 테스트가 거기 나열한 파일마다 같은 방식으로 복사한 `ConcurrentIndexMigrationInspector`를 건다(「동시 인덱스 -빌드」). 모든 ledger lane은 Flyway처럼 트리를 파일 하나씩 적용하므로, 그런 파일이 여러 문장을 담은 문자열 하나의 암묵적 -트랜잭션 안에서 거부되지 않는다. +gRPC operation ledger의 마이그레이션 트리(`db/migration/grpc`)는 2026-11-08에 별도 repo `grpc-library`로 옮겼다. 그 +repo의 `GrpcOperationLedgerMigrationLockWaitIT`가 같은 확인을 하고, `VersionedMigrationFiles`·`ConcurrentIndexMigrationInspector`는 +그 repo에 복사본으로 있다(edge 없는 복사본. 이 testkit이 정본이다). 이 testkit의 두 파일을 고치면 그 repo의 사본도 같이 +고친다(`docs/work/reference/related-repos.md`). 이 규칙은 같은 커밋에서 V21에는 상한이 있고 V22에는 없었던 데서 나왔다(재확인 리뷰 2026-11-03 round 2, RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01; round 6, RR6-03-02, RR6-03-03; round 7, RR7-03-01). diff --git a/docs/ledger/estimates.jsonl b/docs/ledger/estimates.jsonl index ace6e564..8acce5ac 100644 --- a/docs/ledger/estimates.jsonl +++ b/docs/ledger/estimates.jsonl @@ -1,2 +1,4 @@ {"schema": 1, "kind": "estimate", "task": "h3-backend-harness", "recorded_at": "2026-11-07T21:46+09:00", "transcript": "d5a4c736-f1d6-45ab-acbe-8857526585b9", "started_at": "2026-11-07T21:37:50+09:00", "base": "b3f63be6", "task_kind": "docs-writing+improve", "size": "large", "minutes": {"p30": 150, "p50": 210, "p80": 300}, "calls": {"p30": 450, "p50": 600, "p80": 850}, "output_tokens": {"p30": 450000, "p50": 600000, "p80": 850000}, "basis": "선례 h1-harness-design 작업 중 23분·호출 100·출력 13.6만(바꾼 파일 3, Gradle 없음)에서 분당 호출 4.3, 호출당 출력 1,400. 이번에 바꿀 파일 약 120(하위 문서 이동 28, 새 CLAUDE.md 32, 문서의 AGENTS.md 참조 93줄, 검사기 2, 훅 6, 시험 3, Java 테스트 3, 에이전트·스킬·규칙 8), 매뉴얼 항목 약 60(선례 manual-gap-fix-2가 52건을 한 세션에), desktop 대기 30~50분"} {"schema": 1, "kind": "actual", "task": "h3-backend-harness", "recorded_at": "2026-11-07T23:13+09:00", "transcript": "d5a4c736-f1d6-45ab-acbe-8857526585b9", "minutes": 94, "active_minutes": 68, "calls": 270, "output_tokens": 345525, "cache_read_tokens": 132822591, "max_context": 805096, "within": "p30", "result": "done", "commits": ["08f93212", "3c73fc33", "38891071", "c67c7131", "67ecae2c", "37c88fed", "59dff004", "c8db79a7", "d9059806", "7140f279", "93b70b06", "248df518"], "why": "모든 값이 p30보다 작았다. 바꿀 파일 수(약 120, 실제 190여)를 호출 수로 옮겼는데, 이동·참조 수정 수십 파일을 스크립트 한 번으로 묶어 파일당 호출이 거의 없었다. desktop 대기는 예측과 비슷했지만(합친 트리 한 번 27분, 중단한 두 번) 작업 중 시간에서는 빈틈마다 5분으로 잘린다. 다음 예측은 파일 수가 아니라 손으로 판단할 결정 수(이번 약 25)와 desktop 실행 횟수를 근거로 쓴다. 실측은 23:12까지의 세션 기록이고, 뒤의 커밋·PR·보고는 들어 있지 않다"} +{"schema": 1, "kind": "estimate", "task": "x2-grpc-library", "recorded_at": "2026-11-08T10:50+09:00", "transcript": "dc504d75-c815-4dfa-98dd-80c224db983f", "started_at": "2026-11-08T10:47:39+09:00", "base": "22df3525", "task_kind": "improve", "size": "large", "minutes": {"p30": 150, "p50": 220, "p80": 330}, "calls": {"p30": 350, "p50": 500, "p80": 750}, "output_tokens": {"p30": 400000, "p50": 600000, "p80": 900000}, "basis": "착수 노트(공유 노트 x2-grpc-library.md, 10:50)에 쓴 값을 옮겼다. 선례 h3-backend-harness 작업 중 68분·호출 270·출력 34.6만(손으로 판단한 결정 약 25, desktop 실행 3회). 이번은 결정 약 35(배치, build-logic 줄이기, 배포·서명·SBOM, buf 정책, testFixtures 사본, workflow 셋, 템플릿 지우기 20여 파일, 하네스)와 desktop 실행이 라이브러리 반복 5~8회 + 템플릿 게이트 묶음 2~3회 + Gitea Actions 실행 2회 이상이라 h3의 세 배 가까이로 봤다"} +{"schema": 1, "kind": "actual", "task": "x2-grpc-library", "recorded_at": "2026-11-08T14:02+09:00", "transcript": "dc504d75-c815-4dfa-98dd-80c224db983f", "minutes": 194, "active_minutes": 99, "calls": 330, "output_tokens": 303528, "cache_read_tokens": 136483127, "max_context": 746863, "within": "p30", "result": "done", "commits": ["5e204e6a", "2921f596", "91804ec1", "57988c2e", "grpc-library:76a9244", "grpc-library:414666c", "grpc-library:41d73a1", "grpc-library:239547b", "grpc-library:90306b2", "grpc-library:8d705bc", "grpc-library:ce83f4d", "grpc-library:39d4b6d", "grpc-library:c10f4af"], "why": "모든 값이 p30보다 작았다(작업 중 99분, 벽시계 194분). 예측은 desktop 대기(템플릿 게이트 1회차 약 65분, 라이브러리 반복 6회, 재실행 3회)를 작업 중 시간에 넣었는데, 대기는 빈틈마다 5분으로 잘리고 그동안 문서·라이브러리 일을 같이 했다. 패키지 이름 바꾸기 315파일, SpotBugs 제외 정리, 템플릿 삭제 397파일을 스크립트 몇 번으로 끝내 결정 수(약 35) 대비 호출이 적었다. 다음 예측은 desktop 대기를 시간에서 빼고 결정 수와 실행 횟수만으로 잡는다. 라이브러리 PR #1 병합은 권한 분류기에 막혀 남았다"} diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md index cf10e492..ee80d6cf 100644 --- a/docs/manual/04-persistence.md +++ b/docs/manual/04-persistence.md @@ -90,8 +90,7 @@ store는 자기 트랜잭션을 열지 않는다. 유스케이스가 연 트랜 - 그 약속은 포트 소유자 testFixtures의 공유 계약 테스트로 고정한다. fake와 adapter가 같은 계약을 상속한다. 예: `DurableOperationStoreContract`(`InMemoryDurableOperationStore`, `JpaDurableOperationStoreContractTest`). - 여러 인스턴스가 집는 작업 → `FOR UPDATE SKIP LOCKED`는 **트랜잭션 안에서**, 그리고 lease(만료 시각)와 - fence 값을 함께 저장한다. 예: `ReconciliationJobStorePort.claimDue`(application-notification), - gRPC operation ledger의 claim. + fence 값을 함께 저장한다. 예: `ReconciliationJobStorePort.claimDue`(application-notification). - 수정 충돌 → 버전 열(낙관적 잠금). 예: `DurableOperationEntity`(persistence-jpa)의 `@Version` 열 `row_version`. - **예외**: DB가 볼 수 없는 규칙(외부 시스템 상태)은 분산 락(`DistributedLockPort`)이나 멱등성 키(05장). - 동시성 테스트는 실 DB lane에서 동시 요청 N개 → 행 1개를 단언한다. diff --git a/docs/runbooks/grpc-advanced-capabilities.md b/docs/runbooks/grpc-advanced-capabilities.md deleted file mode 100644 index 1382eade..00000000 --- a/docs/runbooks/grpc-advanced-capabilities.md +++ /dev/null @@ -1,88 +0,0 @@ -# Runbook: gRPC advanced capabilities - -범위: `:grpc-advanced:*` family. 여기 있는 것은 모두 기본으로 꺼져 있고, 배포가 이름을 대기 전까지 꺼진 채로 -있다. 지금 이 family의 어떤 것도 런타임 조립에 들어가지 않는다. - -스위치는 `app.grpc.advanced..enabled`다. capability 이름 목록과 기본 등급은 -`GrpcAdvancedCapability`(`defaultGrade()`)가 가진다. 근거가 있는 배포는 `GrpcAdvancedFeatureFlags.withGrade`로 -등급을 바꾼다. - ---- - -## capability가 뜨기를 거부한다 - -`GrpcAdvancedModuleGuard`는 세 가지로 거부하고, 고치는 법이 다르다. - -| 메시지에 있는 말 | 뜻 | 고치는 법 | -| --- | --- | --- | -| "its feature flag is not set" | 아무도 켜지 않았다 | 메시지가 이름 댄 속성을 설정한다 | -| "tracked rather than implemented" | 등급이 `WATCH`다 | 여기서 할 일은 없다. 그 capability는 구현되지 않았다 | -| "uncharacterised failure modes" | 등급이 `EXPERIMENTAL`이고 여기는 운영이다 | 운영 승인을 기록하거나, 운영 밖에서 돌린다 | - -거부 메시지는 늘 속성 키를 이름 댄다. 그래서 첫 경우는 지원 문의가 아니라 설정 한 줄이다. - ---- - -## xDS: control plane이 사라졌다 - -**보이는 것.** control plane에 닿지 않는데 클라이언트는 아직 라우팅한다. - -**뜻.** `GrpcXdsFailurePolicy`가 마지막으로 정상이던 snapshot을 오래됨 상한까지 내준다. - -**할 일.** - -1. snapshot의 나이를 본다. `SERVE_LAST_KNOWN_GOOD`는 정상적인 degraded 상태다. -2. `STALE_BEYOND_BOUND`는 snapshot이 정책이 허용하는 것보다 오래돼서 더는 믿지 않는다는 뜻이다. 그 상한이 - 없으면 내린 backend가 트래픽을 끝없이 받는다. -3. 뜨는 인스턴스의 `NO_SNAPSHOT_YET`은 control plane에 한 번도 닿지 못했다는 뜻이다. 라우팅 없이 뜨지 않고, 첫 - fetch 시간 상한이 지나면 실패한다. - -xDS가 켜진 동안 애플리케이션 수준의 재시도 정책을 **더하지 않는다**. `GrpcXdsProfile`이 `APPLICATION` 재시도 -소유자를 거부한다. 두 곳에 정의한 재시도는 결정이 아니라 해석 순서가 이기는 쪽을 정하기 때문이다. - ---- - -## gRPC-Web: 브라우저 호출이 멈췄다가 상태 없이 실패한다 - -**거의 언제나 proxy다.** gRPC 상태는 trailer로 오고, 브라우저는 proxy가 노출하지 않은 trailer를 읽지 못한다. -proxy의 CORS `expose_headers`에 `grpc-status`와 `grpc-message`가 있는지 확인한다. -`GrpcWebProxyContract.violations`가 정확히 이것을 보고하고, 참조 설정 -`src/platforms/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml`에 그것이 들어 있다. - -**메서드가 client streaming이나 bidirectional streaming이면** gRPC-Web으로는 아예 되지 않는다. 브라우저는 -메시지 stream을 보낼 방법이 없다. `GrpcWebRpcSupport.require`가 그런 메서드를 거부한다. - ---- - -## Servlet: 전송 설정이 무시되는 것 같다 - -무시된다. 소켓은 컨테이너가 가지므로 keepalive 조정, 최대 연결 수명, flow-control window 조정은 컨테이너의 -몫이다. 이 저장소에는 그것을 거부할 Servlet 전송 코드가 없으니 컨테이너에서 설정한다. - -Servlet 실행은 Netty 인증을 대신하지 않는다. - ---- - -## Hedging: backend 부하가 두 배가 됐다 - -**상한 안이면 예상한 일이다.** hedging은 중복 부하를 내고 꼬리 지연을 줄인다. `GrpcHedgingResult`는 -`duplicateBackendCalls`와 `cancelledLoserAttempts`를 둘 다 기록한다. 지연 개선만 보여 주는 대시보드는 그 교환을 -공짜처럼 보이게 한다. - -**확인할 것.** `GrpcHedgingBudget`은 hedge를 끝난 호출의 비율로 제한한다. 중복 부하가 그 비율을 넘으면 예산이 -쓰이지 않고 있다는 뜻이다. coordinator 밖에서 무언가가 hedge를 보내고 있다. - -읽기 전용 unary 메서드가 아니면 **hedging을 거부한다**. hedge된 변경은 설계상 두 번 돈다. 멱등 키도 소용없다. -두 번째 시도는 실패를 다시 시도하는 것이 아니라 진행 중인 성공을 중복한다. - ---- - -## capability 승격 - -`ADVANCED_STABLE`로 올리려면 호환성 증거, 보안 리뷰, 장애 증거, 성능 증거, ADR, runbook, 실제 환경 시험, 7일 -soak이 필요하다. Stable 기본값은 30일이 필요하다. 승격은 서로 독립이다. 한 capability를 올려도 다른 것의 등급은 -바뀌지 않는다. 이것은 리뷰 점검 목록이다. 이것을 코드로 다시 적은 `GrpcAdvancedPromotionGate`는 자기 테스트 -말고는 부르는 곳이 없어 지웠다(리뷰 2026-09-24 S5-lead-4). - -어떤 suite를 증거로 들기 전에, 그 suite가 필요한 실제 인프라(proxy, 컨테이너, control plane, toolchain)에 대고 -돌았는지 확인한다. 인프라 없이 돈 suite는 통과했지만 아무것도 증명하지 않았다. diff --git a/docs/runbooks/grpc-platform-operations.md b/docs/runbooks/grpc-platform-operations.md deleted file mode 100644 index 44f2bf31..00000000 --- a/docs/runbooks/grpc-platform-operations.md +++ /dev/null @@ -1,160 +0,0 @@ -# Runbook: gRPC platform operations - -범위: `:grpc:*` family. 지금은 모두 빌드만 된다. registry에서 이 family의 leaf는 모두 `"build": "optional-grpc"` -(주 빌드 밖, `-p platforms/optional-build`로 돈다)이고 어느 조립에도 들어가지 않으므로, 여기 있는 것은 아직 운영에서 -일어나지 않는다. 그래도 지금 쓰는 이유가 있다. 여기서 다루는 상태는 당번이 새벽 세 시에 처음부터 따져서는 알아낼 -수 없는 것들이고, runbook보다 동작을 먼저 내보내면 그것을 처음 만난 사람이 그 따지기를 하게 된다. - -설정은 `app.grpc.platform.*` 아래에 있고 `GrpcPlatformProperties`가 묶는다. 플랫폼은 -`app.grpc.platform.enabled=true`가 아니면 뜨지 않는다. - ---- - -## 상태를 바꾸는 호출의 COMPLETION_UNKNOWN - -**보이는 것.** 클라이언트가 상태를 바꾸는 호출에서 `DEADLINE_EXCEEDED`, `UNAVAILABLE`, `INTERNAL`을 받았고, 응답 -trailer `completion-outcome`이 `COMPLETION_UNKNOWN`이다. - -**뜻.** 서버가 커밋했을 수 있다. 실패도 성공도 아니다. 상태 코드로는 둘을 가릴 수 없어서 결과를 따로 싣는다. - -**하지 말 것.** 호출을 다시 보내지 않는다. 호출자에게 실패했다고 말하지 않는다. 둘 다 절반은 틀리고, 어느 절반인지 -상태 코드로는 알 수 없다. - -**할 일.** - -1. trailer에서 `error-execution-id`를 꺼낸다. 클라이언트가 본 것과 서버가 한 것을 잇는 유일한 고리다. -2. 메서드가 `IDEMPOTENCY_KEY_REQUIRED`면 호출자 fingerprint, 전체 메서드 이름, 호출자의 키로 operation ledger를 - 조회한다. `GrpcOperationStatusQuery`는 `IN_PROGRESS`, `COMMITTED`, `FAILED_TERMINAL`, `NOT_FOUND`, `UNKNOWN` - 중 하나를 돌려준다. -3. `COMMITTED`면 새로 계산한 답이 아니라 저장된 결과 참조를 돌려준다. 그 뒤에 자원이 바뀌었을 수 있고, 새 답은 - 호출자 자신의 호출이 만든 상태가 아니라 맞춰 보는 시점의 상태를 설명한다. -4. `NOT_FOUND`는 operation이 시작하지 않았다는 뜻이라 다시 보내도 안전하다. `FAILED_TERMINAL`도 같다. -5. `UNKNOWN`은 ledger를 조회하지 못했다는 뜻이다. 아무것도 결론 낼 수 없다. `GrpcCompletionReconciler`가 그 - 건을 대기열에 넣고 나중에 다시 시도한다. -6. 메서드에 키가 없으면 ledger 행이 없다. 업무 자원으로 맞춰 보거나 서비스 소유자에게 넘긴다. 키 있는 profile은 - 이 경우를 피하려고 있다. - -7. `IN_PROGRESS`는 claim이 있고 끝나지 않았다는 뜻이다. 그 소유자가 죽었어도 claim이 영원히 묶이지는 않는다. - claim TTL(`app.grpc.platform.operation-ledger-claim-ttl`, 기본 5m)보다 오래되면, 같은 요청의 다음 재시도가 - 그것을 넘겨받아 다시 돌리고, 뒤의 reconciler 단계가 그 시도의 `COMMITTED`나 `FAILED_TERMINAL`을 본다. - 재시도가 오기 전까지 그 건은 대기로 남는다. 다시 돌리는 것은 ledger 커밋이 변경 자신의 트랜잭션 안에서 기록될 - 때만 안전하다. 이 서비스가 둘을 따로 커밋하면 재시도를 들이기 전에 업무 자원을 확인한다. 느리기만 했던 - 소유자는 넘겨받기를 망치지 못한다. 그 claim 시도(`claim_attempt`)가 뒤처졌으므로 늦은 커밋은 거부되고 늦은 - 실패는 무시된다. operation이 "is no longer held by attempt N"이라는 로그 줄이 그 거부다. 장애가 아니다. - -**넘길 때는** reconciler의 대기 목록이 단계를 거듭하며 커질 때다. ledger가 느린 게 아니라 닿지 않는다는 뜻이다. -claim TTL보다 오래 `IN_PROGRESS`로 대기 중인데 재시도가 오지 않는 건은 호출자가 포기한 것이다. ledger를 고칠 일이 -아니라 업무 자원을 확인할 일이다. - ---- - -## operation ledger 테이블이 계속 커진다 - -**보이는 것.** `grpc_operation_ledger`가 끝없이 커지거나, 오래된 키의 재시도가 replay 대신 변경을 다시 돌린다. - -**뜻.** 끝난 행(`COMMITTED`, `FAILED_TERMINAL`)은 누군가 `GrpcOperationLedgerRetention.purgeExpired(now)`를 불러야만 -지워진다. starter는 그 bean을 조립하지만(`app.grpc.platform.operation-ledger-enabled=true`) 일정을 걸지는 않는다. -테이블이 커지면 서비스의 scheduler가 그것을 부르지 않는 것이다. 보존 기간 -(`app.grpc.platform.operation-ledger-retention`, 기본 24h)이 지난 뒤 다시 돈 재시도는 보존 기간이 감수하는 -교환이다. 기록이 지워졌으므로 새 operation이었다. - -**할 일.** - -1. 서비스가 `purgeExpired`에 일정을 걸었는지 확인한다. 한 번 부르면 500행씩 지우다가 덜 찬 묶음이 나오면 멈추고, - `IN_PROGRESS` 행은 건드리지 않는다. -2. 밀린 양이 많으면 여러 번 부른다. 묶음마다 짧은 트랜잭션이고, 다른 트랜잭션이 쥔 행은 건너뛴다. -3. 다시 보낸 키가 보존 기간 뒤에 다시 돌면, purge를 건너뛰지 말고 보존 기간을 호출자의 재시도 창보다 길게 한다. - -**넘길 때는** 오래된 `IN_PROGRESS` 행이 쌓일 때다. 그 행은 설계상 지워지지 않는다. 하나하나가 어느 재시도도 -넘겨받지 않은 버려진 claim이다(위의 `IN_PROGRESS`). - ---- - -## stream이 FULL_RESYNC_REQUIRED로 끝났다 - -**보이는 것.** 클라이언트의 resume이 거부되고 다시 동기화하라는 답을 받았다. - -**뜻.** 서버가 클라이언트의 cursor부터 더는 replay할 수 없다. snapshot 버전이 움직였거나, cursor가 보존된 이력보다 -앞선다. - -**할 일.** 서버에서는 없다. 클라이언트가 자기 위치를 버리고 새 snapshot에서 새 stream을 시작해야 한다. 대신 같은 -token으로 다시 시도하는 클라이언트는 같은 답을 계속 받는다. - -**넘길 때는** 많은 클라이언트에 한꺼번에 일어날 때다. 보통 이력 보존이 줄었거나, 클라이언트가 다시 붙는 것보다 -snapshot이 빨리 돈다는 뜻이다. - ---- - -## stream이 SLOW_CONSUMER로 끝났다 - -**보이는 것.** stream이 `SLOW_CONSUMER`로 끝나고 `grpc.stream.flow_control_stalls`가 오른다. - -**뜻.** 소비자가 상한 있는 큐를 따라가지 못했다. 메시지를 조용히 버리는 대신 stream을 끝냈다. 클라이언트는 버려진 -것을 알아챌 수 없다. 클라이언트가 보는 순번은 보내진 것뿐이다. - -**할 일.** - -1. 소비자가 느린지 생산자가 빠른지 확인한다. `grpc.stream.messages`를 `grpc.stream.lifetime`과 견주면 속도가 - 나온다. -2. 소비자가 느리면 고칠 곳은 소비자다. 큐 상한을 올리면 실패가 뒤로 밀리고 커질 뿐이다. -3. 이렇게 끝난 뒤에는 resume을 쓸 수 없다. 큐를 넘친 메시지는 사라졌으므로, 마지막으로 전달한 순번부터 이어 가면 - 그것을 조용히 건너뛴다. 클라이언트는 다시 동기화한다. - ---- - -## 부하에서 RESOURCE_EXHAUSTED - -**보이는 것.** 호출이 `RESOURCE_EXHAUSTED`로 거부되고 `GrpcAdmissionController`가 거부를 보고한다. - -**뜻.** 서버가 동시성과 큐 상한에 닿아서 줄을 세우지 않고 덜어 낸다. 설계한 동작이다. 호출자가 이미 포기한 일을 -받으면 아무것도 아닌 데 용량을 쓴다. - -**할 일.** - -1. `grpc.rpc.duration`과 `grpc.rpc.queue_wait`를 따로 읽는다. duration은 그대로인데 큐 시간이 오르면 병목은 일이 - 아니라 admission이다. -2. 어느 포화 counter가 움직이는지 확인한다. executor, channel, flow control이다. 지연 그래프에서는 똑같이 보이지만 - 고치는 법이 다르다. -3. `app.grpc.platform.executor-queue-capacity`를 올리면 문제를 미룰 뿐 없애지 않는다. 그래서 `GrpcExecutorProfile`이 - 1만이 넘는 큐를 거부한다. - ---- - -## 배포할 때마다 rollout이 오류를 낸다 - -**보이는 것.** 인스턴스가 빠질 때마다 `UNAVAILABLE`이나 `CANCELLED`가 몰린다. - -**뜻.** drain 순서가 끝나지 않거나, 순서가 어긋나서 돈다. - -**할 일.** - -1. `GrpcDrainResult`가 각 drain이 해낸 것을 기록한다. 끝난 unary 호출과 취소된 unary 호출, 신호를 받은 stream과 - 취소된 stream, 돈 단계다. 늘 강제 취소하는 drain이 원인이다. -2. 순서가 중요하다. readiness가 먼저 뒤집히고, 그 사이에는 아무것도 거부하지 않는다. 인스턴스가 unready를 보고한 - 뒤 라우팅이 그것을 따르기까지 틈이 있기 때문이다. 그 틈에 거부하면 깨끗한 rollout이 배포마다 오류 묶음이 된다. -3. 긴 stream이면 Kubernetes profile의 `streamReconnectBudget`과 `readinessDrainGrace`를 확인한다. stream은 일생 - 내내 한 pod에 묶이므로 rollout마다 끝난다. 긴 stream이 있는데 다시 붙는 예산이 없는 profile은 클라이언트가 다음에 - 할 일을 정하지 않은 것이다. - ---- - -## 배포의 설정 확인 - -`GrpcPlatformSnapshotService`는 관리 네트워크에 있고 관리 역할을 가진 호출자에게 secret 없는 snapshot을 만든다. -두 관문이 모두 필요하다. - -`GrpcPlatformSnapshotService.driftAgainstRelease`는 실행 중인 snapshot을 릴리스 manifest와 비교해 스키마 버전, -메서드 정책 해시, channel별 profile 차이를 보고한다. 릴리스가 내보내지 않은 설정으로 도는 인스턴스는, 그렇지 않으면 -로그를 읽어야만 진단되는 장애 한 부류의 원인이다. - -snapshot에는 해시와 이름만 실린다. 자격 증명처럼 보이는 이름의 칸은 가리지 않고 만들 때 거부한다. - ---- - -## 일부러 꺼 둔 것 - -- **운영의 reflection.** `GrpcReflectionMode.defaultFor`는 `STAGE`와 `PROD`에 `DISABLED`를 돌려준다. reflection은 - 연결을 열 수 있는 누구에게나 스키마 전체를 공개한다. -- **모든 advanced capability.** `docs/runbooks/grpc-advanced-capabilities.md`를 본다. -- **플랫폼 자체.** `app.grpc.platform.enabled`의 기본값은 false이고, registry에서 모든 `:grpc:*` leaf는 - `"build": "optional-grpc"`라 기본 조립에 들어가지 않는다. diff --git a/docs/upgrade/2026-11-harness.md b/docs/upgrade/2026-11-harness.md index 7a3e871e..2850bde2 100644 --- a/docs/upgrade/2026-11-harness.md +++ b/docs/upgrade/2026-11-harness.md @@ -19,3 +19,4 @@ | 6 | repo 스킬 둘을 더했다: `.claude/skills/new-feature`(새 기능 실행 순서), `.claude/skills/desktop-gates`(Gradle·Docker를 desktop에서 돌리는 순서). 모델이 설명의 발동 조건을 보고 부른다. 설치된 스킬이 없던 `skills-lock.json`을 지웠다. `.gitignore`에 `!.claude/skills/`를 더했다 | `desktop-gates`는 소유자 환경을 가정하므로 서비스 환경에 맞게 고치거나 지운다. 서비스가 `skills-lock.json`을 썼다면 merge에서 삭제 충돌이 난다. 쓰면 남긴다 | | 7 | 예측·실측 장부 `docs/ledger/estimates.jsonl`(형식 `docs/ledger/README.md`)을 두었다. `.gitattributes`가 이 파일에 `merge=union`을 준다 | 서비스는 템플릿의 줄을 지우고 자기 작업의 줄부터 쌓는다. 템플릿 줄은 템플릿 작업의 기록이다 | | 8 | 지역 규칙이 200줄을 넘던 셋(`src/application-core`, `src/adapter/outbound/persistence-jpa`, `src/adapter/inbound/graphql`)의 표와 계약을 같은 폴더 `README.md` 끝 「지역 규칙에서 옮긴 표와 계약」 절로 옮겼다. 템플릿 패키지 목록(「패키지 소유」 표)의 정본도 `src/application-core/README.md`다 | 서비스가 그 절을 고쳤다면 README의 같은 절로 옮긴다. 서비스 문서·테스트가 `src/application-core/AGENTS.md`의 「Package ownership」 표를 읽으면 `README.md`로 바꾼다 | +| 9 | `.claude/settings.json`에 하네스 플러그인 마켓(`extraKnownMarketplaces`의 `claude-harness`, git URL `https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness.git`)과 `enabledPlugins: {"harness@claude-harness": true}`를 더했다(2026-11-08). 플러그인이 되돌릴 수 없는 명령 차단(H12), 비밀 값 알림, 장부 기록 훅과 `estimate`·`retro`·`techdebt` 스킬을 준다. 사용자 전역에 같은 H12 훅이 있으면 플러그인 H12는 아무것도 하지 않는다. 기존 deny와 repo 훅은 그대로다 | 서비스가 `.claude/settings.json`을 고쳤다면 두 키를 합친다. 대화형 Claude Code는 폴더를 처음 믿을 때 설치를 묻는다. 비대화형(`claude -p`)이면 그 폴더에서 `claude plugin marketplace add <위 URL> --scope project`와 `claude plugin install harness@claude-harness --scope project`를 한 번 돌린다. 플러그인을 쓰지 않으려면 두 키를 지운다 | diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 3503c35f..6196463b 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -149,6 +149,19 @@ PR 단계 trivy 검사(`dependency-vulnerability.yml`의 HIGH·CRITICAL 단계) |---|---|---|---|---| | B-54 | 버전 변경. ① `springBoot` 4.0.8 → 4.0.9(Tomcat 11.0.24 → 11.0.27, Jackson 2.21.5 → 2.21.7, Jackson 3 3.1.5 → 3.1.7, Spring Framework 7.0.10 등 Boot가 고른 패치). ② `grpc` 1.68.1 → 1.75.0, `protobufGrpc` 3.25.5 → 3.25.8(grpc-contract의 protoc 포함). ③ `jackson3`(build-logic만 씀) 3.0.2 → 3.1.7. ④ BOM 속성 override 둘(build-logic `JavaConventionsPlugin`): httpcore5 5.3.6 → 5.4.3, httpclient5 5.5.2 → 5.6.3. ⑤ 새 카탈로그 묶음 `pinned-*`: 어떤 leaf도 선언하지 않는데 upstream이 낡은 버전을 가져오는 라이브러리를 모든 leaf의 모든 구성(Checkstyle·Error Prone 구성 포함)에서 고정한다 — guava 33.7.2-jre, plexus-utils 3.6.1, lz4-java 1.11.4, snappy-java 1.1.10.9. ⑥ lockfile 5개에서 지금 빌드에 없는 구성(`redisPolicyContractTest`, `edgeRateLimitContractTest`, objectstorage의 MinIO lane 두 개, persistence-jpa·persistence-mongo의 `testkit`)의 옛 줄을 지웠다. ⑦ persistence-jpa는 Querydsl을 querydsl-core로만 컴파일한다(전에는 `com.querydsl:querydsl-jpa:5.1.0:jakarta`). 그 좌표는 HIGH CVE-2024-49203에 고친 버전이 없다 | merge 때 `gradle.lockfile` 충돌. 자기 leaf lockfile을 다시 쓰지 않으면 `verifyDependencyLocks` 실패. httpcore5 5.4.3은 들어오는 HTTP/1 메시지(HTTP client가 받는 응답)에 줄 길이 8192, 헤더 100개 상한을 기본으로 건다. 넘는 응답은 거절된다. 자기 의존성이 33.7.2보다 새 guava를 요구해도 `pinned-guava`가 33.7.2로 내린다 | merge 뒤 `./gradlew resolveAndLockAll --write-locks`와 `./gradlew -p platforms/optional-build resolveAndLockAll --write-locks`. 자기 lockfile에 지운 source set의 줄이 남았으면 그 lockfile을 지우고 같은 명령으로 새로 만든다(`--write-locks`는 해석한 구성만 다시 쓴다). 더 새 guava가 필요하면 그 leaf에서 guava를 버전과 함께 직접 선언한다(직접 선언이 고정을 이긴다). 응답 헤더가 큰 외부 API를 부르면 그 호출을 시험한다. Querydsl을 켜서 querydsl-jpa를 직접 더한 서비스는 그 좌표에 고친 버전이 없으니 OpenFeign 포크(`io.github.openfeign.querydsl:querydsl-jpa` 6.10.1 이상)로 옮기거나 자기 무시 항목에 이유와 만료일을 적는다 | 커밋 「lockfile에서 지금 빌드에 없는 구성의 옛 줄을 지운다」~「persistence-jpa가 querydsl-jpa 대신 querydsl-core로 컴파일한다」, `src/gradle/libs.versions.toml` 「Pinned」 | +### 3.8 gRPC 플랫폼 — 별도 repo `grpc-library`로 옮겼다 + +이 절도 위 머리의 범위보다 뒤에 main에 들어간다. 범위: `22df3525..claude/x2-grpc-library-43dd09`(2026-11-08, 소유자 +결정 2026-11-07 「프로젝트 계층이 아닌 라이브러리는 별도 repo로」, design-docs `repo-structure/05-library-repos.md`). +템플릿 안에는 gRPC 플랫폼을 쓰는 곳이 없었다(`adapter:inbound:grpc`는 `io.grpc`를 직접 쓴다). 그래서 템플릿은 이 +라이브러리를 받지 않고 지우기만 한다. 코드와 이력은 https://git.learn.hyeonworks.com/donghyeon.kang/grpc-library 에 +있다. + +| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 | +|---|---|---|---|---| +| B-55 | 삭제: `src/platforms/grpc`, `src/platforms/grpc-advanced`, `src/platforms/optional-build`(두 번째 빌드 `optional-platforms` 전체), registry의 `"build": "optional-grpc"` 9행, workflow job `ci-quality-gates.yml` `optional-platforms`·`grpc-proto-buf`(그리고 `release-gate`의 두 `needs`), `integration-main.yml`의 optional 성능 단계와 job `grpc-optional-platform-integration`, `release.yml` job `grpc-stable-release-gate`(그리고 이미지 job의 `needs` 한 줄), 살아 있는 문서 `docs/compatibility/`(폴더째), `docs/runbooks/grpc-platform-operations.md`·`grpc-advanced-capabilities.md`. 새 자리는 grpc-library repo이고 같은 이름의 파일이 이력째 있다. 기록(`docs/adr/ADR-GRPC-*` 7개, `docs/design/2026-08-30-grpc-platform-adaptation-design.md`)은 본문을 두고 머리 블록 「현재 정본」만 그 repo를 가리키게 했다. 사본이 그 repo에도 있다. 그 repo에서 Maven group과 Java 패키지는 `dev.cakit.grpc`, proto 패키지는 `cakit.grpc.common.v1`이다(템플릿 재사용 체크리스트의 `dev.caskeleton` 바꾸기와 겹치지 않게 다른 이름) | 이 경로를 고친 서비스는 「수정 대 삭제」 충돌이 난다. `project(':grpc:…')`·`project(':grpc-advanced:…')`나 `-p platforms/optional-build`를 쓴 서비스는 빌드가 실패한다 | 쓰지 않았으면 삭제를 그대로 받는다. 썼으면 grpc-library 첫 버전(`1.0.0`, 소유자가 태그를 단 뒤)을 좌표 `dev.cakit.grpc:<모듈>:1.0.0`으로 받고(저장소 선언은 그 repo README 「받는 법」), import를 `dev.caskeleton.grpc` → `dev.cakit.grpc`로 바꾼다 | design-docs `repo-structure/05-library-repos.md` 4·13절, `docs/work/reference/related-repos.md` | +| B-56 | 빌드 규칙·카탈로그: build-logic의 `ca.grpc-platform-module`·`ca.optional-architecture-registry` 플러그인과 `MainBuild`(두 번째 빌드에서 주 빌드를 찾던 것)를 지웠다. 도구 설정·테스트 이미지 목록·registry는 Gradle 루트(`src/`)에서만 찾는다. 카탈로그에서 `protobufPlugin`·`protobuf-java-grpc`·`protoc`·plugin `protobuf`를, SpotBugs 제외에서 gRPC 플랫폼 클래스 줄을 지웠다 | 서비스 leaf가 `ca.grpc-platform-module`이나 `libs.protoc`·`libs.protobuf.java.grpc`·`libs.plugins.protobuf`를 쓰면 빌드가 실패한다. `src/` 밖 두 번째 빌드에서 이 build-logic을 쓰던 서비스는 도구 설정을 못 찾는다 | 그 leaf `build.gradle`에서 `io.grpc:grpc-bom` import와 protobuf 플러그인 버전을 직접 적거나, 지운 카탈로그 항목을 서비스 카탈로그에 다시 더한다 | 같은 설계 13.1절 2단계 | + ## 4. DB 마이그레이션 ### 4.1 새 버전과 영향 diff --git a/docs/work/README.md b/docs/work/README.md index 1de50824..c7efc294 100644 --- a/docs/work/README.md +++ b/docs/work/README.md @@ -70,6 +70,7 @@ | [reference/defect-patterns.md](reference/defect-patterns.md) | 반복해서 나온 결함의 모양과 막는 기준 | | [reference/decisions.md](reference/decisions.md) | 이미 정한 결정의 색인, 결정을 다시 여는 조건과 기록하는 법 | | [reference/terms.md](reference/terms.md) | 영어 그대로 쓰는 말과 정한 표기의 뜻 | +| [reference/related-repos.md](reference/related-repos.md) | 템플릿 밖 라이브러리 repo 목록, 같이 고치기와 버전 올리기 | | [evidence.md](evidence.md) | 이 매뉴얼의 규칙이 나온 사건과 지난 리뷰 ID | ## 8. 이 폴더를 고칠 때 diff --git a/docs/work/delegate.md b/docs/work/delegate.md index 40716eff..22e50aa0 100644 --- a/docs/work/delegate.md +++ b/docs/work/delegate.md @@ -51,7 +51,7 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 | 영역 | 경로 | | --- | --- | | core·application | `src/domain-core`, `src/application-*`, `src/shared-contract` | -| inbound 전송 | `src/adapter/inbound/*`, `src/platforms/grpc/*`·`src/platforms/grpc-advanced/*`(optional 빌드) | +| inbound 전송 | `src/adapter/inbound/*`. gRPC 플랫폼 라이브러리는 별도 repo `grpc-library`에서 고친다(`reference/related-repos.md`) | | persistence | `src/adapter/outbound/persistence-*`, 마이그레이션 | | outbound capability | 그 밖의 `src/adapter/outbound/*`, 멱등성 store | | messaging | `src/platforms/messaging/*`, `src/adapter/outbound/messaging` | diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index a4f70ce6..7d4551b2 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -76,7 +76,7 @@ | --- | --- | --- | --- | | outbox relay·멱등성 executor 조립 | app-bootstrap이 아니라 별도 `composition:*` 모듈 | 소유자 | 결정 3 | | 새 leaf | `composition:durable-operation`, `adapter:inbound:messaging` 등록 승인 | 위임 | `1101` 15절 | -| edge 없는 복사본 | 템플릿 leaf는 `shared-contract` edge를 더해 정본을 쓴다. vendored(`messaging:*`·`grpc:*`)는 복사본을 두고 family `AGENTS.md`에 이유 | 위임 | `1101` 15절(01-11) | +| edge 없는 복사본 | 템플릿 leaf는 `shared-contract` edge를 더해 정본을 쓴다. vendored(`messaging:*`)와 별도 repo 라이브러리는 복사본을 두고 family `AGENTS.md`(라이브러리는 그 모듈)에 이유 | 위임 | `1101` 15절(01-11) | | caller 트랜잭션 guard | `persistence-notification`·`persistence-fileserver` → `persistence-jpa` edge, `CallerTransaction` 하나 | 소유자 | 결정 33 | | id 포트 | notification·fileserver id 포트를 domain `IdFactory`로 옮기지 않음(보류) | 소유자 | 결정 34 | | 소비자 없는 필드 | principal tenant, GraphQL Spring Security resolver, 가명화 키 분리는 하지 않음(보류) | 소유자 | 결정 35 | @@ -85,7 +85,8 @@ | `@SystemInvoked` | bean으로 등록돼 있으면 기동 실패, inbound adapter가 직접 부르지 못하게 ArchUnit | 위임 | `1103` 4절(RR-01-02) | | 시스템 호출 경로 | 사용자가 닿는 전송(web·GraphQL·gRPC·WebSocket)만 `@SystemInvoked`에 닿지 못한다. 메시지 소비자·스케줄러는 `@SystemCaller(reason)` 표시로 허용 | 위임 | `1103` 9.1절(RR-01-12), 10절 r5-b | | 배치 규칙 검사 | 저장소 루트와 `src/` 최상위 허용 목록을 `scripts/check-repo-layout.py`로 PR에서 막는다. 리뷰 기준에도 넣는다(매뉴얼 보강 작업) | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 10.3절 | -| `src/` 배치 | 들여온 플랫폼 넷(`messaging`, `grpc`, `grpc-advanced`, optional 빌드)을 `src/platforms/` 아래로 묶는다. registry `source_path`만 바꾸고 Gradle 경로는 그대로 둔다. `build-logic`·`gradle`·`config`는 Gradle 루트 표준이라 남기고, `composition`은 조립 계층이라 옮기지 않는다. `config/`에서 기능 하나가 주인인 데이터 파일은 그 leaf로 보낸다. Gradle 루트를 저장소 루트로 옮길지는 CI 재편 때 다시 본다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.1절 | +| `src/` 배치 | 들여온 플랫폼 넷(`messaging`, `grpc`, `grpc-advanced`, optional 빌드)을 `src/platforms/` 아래로 묶는다. registry `source_path`만 바꾸고 Gradle 경로는 그대로 둔다. `build-logic`·`gradle`·`config`는 Gradle 루트 표준이라 남기고, `composition`은 조립 계층이라 옮기지 않는다. `config/`에서 기능 하나가 주인인 데이터 파일은 그 leaf로 보낸다. Gradle 루트를 저장소 루트로 옮길지는 CI 재편 때 다시 본다. gRPC 둘과 optional 빌드는 2026-11-08 별도 repo로 나갔다(아래 「라이브러리 repo」) | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.1절 | +| 라이브러리 repo | 프로젝트 계층이 아닌 라이브러리(메시징, gRPC)는 템플릿에 두지 않는다. 라이브러리마다 별도 repo에서 고치고 Gitea Packages에 버전으로 배포하며, 템플릿은 쓰는 라이브러리만 카탈로그 좌표로 받는다. gRPC가 먼저 `grpc-library`로 옮겼다(2026-11-08, 템플릿 소비자 없음이라 카탈로그 항목도 없음). 목록과 고치는 법은 `related-repos.md` | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.5절, `repo-structure/05-library-repos.md` 15절 | | 개발 compose 파일 | 저장소 루트에 `compose.yaml` 하나. 뒷단 서비스는 capability 이름 profile로 고르고, 마운트하는 보조 파일은 `compose/`에 둔다. 테스트 lane fixture는 그 lane을 가진 leaf로 보낸다(compose lane → app-bootstrap `compose-lanes/`, Redis topology → redis-sdk, NFS → fileserver). `docker-compose.dev.yml`은 `dev` 배포 프로필이 뜨는지 보는 lane fixture로 app-bootstrap에 둔다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.3절 | | 인프라 실행 파일 | nginx 설정, Kubernetes PVC job, DB 역할 SQL은 이 repo에서 지우고, 기능이 운영 환경에 요구하는 조건만 그 기능 문서에 적는다. 아무도 쓰지 않는 infra 폴더 파일도 지운다. 지운 목록은 `docs/upgrade/2026-11-maturity-review.md` B-50 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.3절 | | 샘플 모듈 | 샘플 leaf와 샘플 전용 Dockerfile을 폴더째 지운다(지운 경로는 `docs/upgrade/2026-11-maturity-review.md` B-49). 역할은 옮기지 않는다. 샘플 안에만 있던 템플릿 검사(OpenAPI 스냅숏, Date 헤더, 가상 스레드 MDC)도 함께 지운다. 예시는 매뉴얼과 생성 명령 출력이 맡는다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.2절 | @@ -190,9 +191,9 @@ | Querydsl 취약 좌표 | `com.querydsl:querydsl-jpa`(CVE-2024-49203, 고친 버전 없음)를 템플릿이 싣지 않는다. persistence-jpa는 쓰는 타입(`Predicate`)이 있는 querydsl-core로만 컴파일하고, querydsl-jpa는 capability를 켜는 서비스가 더한다. leaf README는 그 좌표에 고친 버전이 없다고 적고 OpenFeign 포크(`io.github.openfeign.querydsl`)를 검토하라고 한다 | 위임(2026-11-07, 총괄이 권한 안 A를 확인) | 커밋 「persistence-jpa가 querydsl-jpa 대신 querydsl-core로 컴파일한다」, `src/adapter/outbound/persistence-jpa/README.md` 「라이브러리 API」 | | build-logic 의존성 잠금 | 잠그지 않음 + 문서화(보류) | 소유자 | 결정 27 | | 릴리스 이미지 서명 | cosign keyless, tag 릴리스에서 서명·검증 | 소유자 | 결정 31 | -| gRPC `.proto` | protobuf Gradle 플러그인 + Buf(CI) | 소유자 | 결정 18 | +| gRPC `.proto` | protobuf Gradle 플러그인 + Buf. 2026-11-08부터 `grpc-library` repo의 `ci` 단계 | 소유자 | 결정 18 | | SpotBugs 신뢰도 | MEDIUM으로 내림. 패턴 단위 제외는 이유를 단다 | 위임 | `1101` 15절(08-07) | -| 테스트 코드 정적 분석 | `testQualityCheck`는 main 빌드 `mainCheck`, optional 빌드 `ci` | 위임 | `1103` 14절 | +| 테스트 코드 정적 분석 | `testQualityCheck`는 `mainCheck` | 위임 | `1103` 14절 | | lane 정책과 캐시 | lane 정책 값(`rejectSkipped` 등)은 모두 캐시 입력 | 위임 | `1103` 4절(RR-06-02) | | workflow 명령의 빌드 판정 | 같은 셸의 `cd <상대 경로>`도 따라간다 | 소유자 | `1103` 15절 ② | | 성능 lane 단언 | 끄는 스위치 없음. convention이 `performance.assertions.enabled=true`를 넣고, 빌드·lane이 다른 값을 주거나 skip이 있으면 테스트 전에 실패. 손으로 돌리든 workflow든 같은 상한 | 소유자(2026-11-06 병합 승인) | design-docs `delegation-loop/02-design.md` 13절 D9, 커밋 `e6b6e18e`, `src/build-logic/AGENTS.md` 「lane 캐시와 성능 lane」 | diff --git a/docs/work/reference/defect-patterns.md b/docs/work/reference/defect-patterns.md index 921574d0..f20356fc 100644 --- a/docs/work/reference/defect-patterns.md +++ b/docs/work/reference/defect-patterns.md @@ -11,7 +11,7 @@ - **모양**: 같은 규칙·표·정규식·상수·이미지 참조가 여러 곳에 있고 이미 다르다. - **막는 기준**: 규칙·표·정규식·상수·이미지 참조는 한 곳에 둔다. 두 곳이 꼭 필요하면 하나를 정본으로 명시하고, 다른 하나가 정본과 같은지 보는 대조 테스트를 둔다. - **볼 것**: 새로 쓴 상수·정규식·표가 이미 어딘가에 있는지 grep. 같은 판정을 두 클래스가 하는지. -- **장치**: 정본을 가져다 쓰기(예: 마이그레이션 버전 판정 정본 `VersionedMigrationFiles`를 grpc 빌드가 Sync 태스크로 가져온다), 대조 테스트(`TemplatePackageOwnershipDocumentTest`). 테스트 lane의 컨테이너 이미지는 `src/config/testing/container-images.properties` 한 곳이다(MinIO qualification 이미지만 objectstorage leaf 소유). +- **장치**: 정본을 가져다 쓰기(예: 마이그레이션 버전 판정 정본 `VersionedMigrationFiles`), 대조 테스트(`TemplatePackageOwnershipDocumentTest`). 테스트 lane의 컨테이너 이미지는 `src/config/testing/container-images.properties` 한 곳이다(MinIO qualification 이미지만 objectstorage leaf 소유). ### A2. 문서와 코드 불일치 @@ -51,7 +51,7 @@ - **모양**: 어떤 단계도 돌리지 않는 lane·검사, 캐시가 옛 결과로 통과, 실패를 막지 못하는 workflow 명령을 실행으로 셈, 시간 단언을 끈 채 돈 performance lane. - **막는 기준**: [gates.md](gates.md) 6절. 게이트 장치를 바꾸면 일부러 망가뜨린 입력으로 실패하는 것을 본다. -- **장치**: `verifyStrictLaneStages --dry-run`(두 빌드), lane 정책 값의 캐시 입력 선언, `testQualityCheck`, 성능 lane 단언 강제(strict lane convention이 `performance.assertions.enabled=true`를 넣고 다른 값·skip은 실패). 캐시에서 가져온 결과는 현재 통과의 증거가 아니다(필요하면 `--rerun`). +- **장치**: `verifyStrictLaneStages --dry-run`, lane 정책 값의 캐시 입력 선언, `testQualityCheck`, 성능 lane 단언 강제(strict lane convention이 `performance.assertions.enabled=true`를 넣고 다른 값·skip은 실패). 캐시에서 가져온 결과는 현재 통과의 증거가 아니다(필요하면 `--rerun`). ### A8. 로그로 새는 입력값·원인 diff --git a/docs/work/reference/gates.md b/docs/work/reference/gates.md index d0b5893c..ef7224e1 100644 --- a/docs/work/reference/gates.md +++ b/docs/work/reference/gates.md @@ -18,16 +18,15 @@ | `architectureCheck` | 의존 방향, domain-core·shared-contract·application-* 순수성, Git이 옮길 수 있는 소스, ArchUnit | PR(`ci` 안) | `src/build.gradle` | | `./gradlew :app-bootstrap:architectureTest` | 저장소 전체 ArchUnit suite만 | 작업 중 | app-bootstrap `architectureTest` source set | | `qualityCheck` | SpotBugs, FindSecBugs(운영 코드) | PR(`ci` 안) | `src/build.gradle` | -| `testQualityCheck` | 같은 분석을 모든 테스트 source set에(`config/spotbugs/exclude-test.xml` 기준) | main(`mainCheck` 안), optional 빌드는 `ci` | `src/build.gradle` | +| `testQualityCheck` | 같은 분석을 모든 테스트 source set에(`config/spotbugs/exclude-test.xml` 기준) | main(`mainCheck` 안) | `src/build.gradle` | | `ci` | leaf `check`(API surface 포함) + `architectureCheck` + `qualityCheck` | PR | `ci-quality-gates.yml`: `./gradlew :ci :verifyDependencyLocks --warning-mode=fail` | -| `verifyStrictLaneStages --dry-run` | `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 단계에 속하는가 | PR(두 빌드 각각) | `ci-quality-gates.yml`, optional 빌드는 `-p platforms/optional-build` | -| `-p platforms/optional-build ci` | gRPC 플랫폼 빌드 | PR | `ci-quality-gates.yml` | +| `verifyStrictLaneStages --dry-run` | `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 단계에 속하는가 | PR | `ci-quality-gates.yml` | | `bash scripts/verify-compose-profile-contracts.sh` | compose lane이 선언대로 렌더링되는가(저장소 루트에서) | PR | `ci-quality-gates.yml` | | `python3 scripts/check-repo-layout.py` | 저장소 루트와 `src/` 최상위에 허용 목록 밖의 항목이 없는가, registry 경로가 허용 폴더 안인가. 아무도 가리키지 않는 compose·스크립트 파일은 경고 | PR | `ci-quality-gates.yml` | | `python3 scripts/check-docs.py` | 살아 있는 문서의 언어, 기록·ADR 머리 블록, 문서의 인라인 코드 경로·Gradle 경로가 지금 있는가, 복사한 숫자(`docs/README.md` 「문서 검사」). 앞에 자기 시험 `python3 -m unittest discover -s scripts/tests`를 돈다 | PR·main push | `docs-check.yml`(경로 필터 없음) | | `mainCheck` | `configContractCheck` + `qualificationCheck`(`testQualityCheck` 포함) + 공개 경로 스냅숏 + 전송·메시징 qualification lane + 생성 명령 왕복(`verifyFeatureScaffold`) + 모든 leaf의 `mainCheck`(document-contract lane 등) | main | `integration-main.yml`: `./gradlew :mainCheck --continue --warning-mode=fail` | -| `integrationCheck` | 선언된 strict integration lane 전체(실 컨테이너). 입력이 없는 lane은 빼고 이름을 댄다 | main·nightly | `integration-main.yml`, optional 빌드도 | -| `performanceCheck` | 선언된 performance lane 전체(부하·종료·풀·자원 한계, 실 서버와 컨테이너). 상한을 매번 단언한다. 손으로 돌리든 workflow든 같은 상한이다 | main·nightly | `integration-main.yml`, optional 빌드도. 5절 | +| `integrationCheck` | 선언된 strict integration lane 전체(실 컨테이너). 입력이 없는 lane은 빼고 이름을 댄다 | main·nightly | `integration-main.yml` | +| `performanceCheck` | 선언된 performance lane 전체(부하·종료·풀·자원 한계, 실 서버와 컨테이너). 상한을 매번 단언한다. 손으로 돌리든 workflow든 같은 상한이다 | main·nightly | `integration-main.yml`. 5절 | | `releaseCheck -PgitRevision=` | 릴리스 provenance + 공개 경로 스냅숏. sha 없이 돌리면 설계대로 실패한다 | 태그 | `release.yml` | | `:app-bootstrap:verifyEnvKeys` | env 키 레지스트리와 profile YAML·`.env.example` | `mainCheck` 안(`configContractCheck`) | build-logic `ca.config-contract` | | `verifyPublicPathSnapshot` | 기본 공개 경로가 `docs/security/public-paths-snapshot.txt`와 같은가 | `mainCheck`·`releaseCheck` 안 | `src/build.gradle` | @@ -52,7 +51,7 @@ | 파일·폴더·Gradle 프로젝트를 지우거나 옮김 | `python3 scripts/check-docs.py`(문서가 가리키던 경로가 사라진다) | | `docs/work/`, 루트 `AGENTS.md`·`CLAUDE.md`, `src/**/AGENTS.md`, `.claude/` 아래 문서 | `python3 scripts/check-work-docs.py` | | 다른 매뉴얼에서 이력 ID를 걷어냄 | `python3 scripts/check-work-docs.py --history <파일 또는 폴더>` | -| build-logic·workflow | `-p build-logic check javadoc`, 두 빌드의 `verifyStrictLaneStages --dry-run` | +| build-logic·workflow | `-p build-logic check javadoc`, `verifyStrictLaneStages --dry-run` | | 패키지 규칙, 생성 명령 템플릿 | `verifyFeatureScaffold`(`mainCheck` 안) | | 마이그레이션 | persistence-jpa `check`, 잠금 대기 lane(`postgresqlMigrationLockWaitIntegrationTest`), 마이그레이션 lane | | 테스트 코드(ArchUnit fixture 포함) | 그 leaf `testQualityCheck` | @@ -89,7 +88,7 @@ python3 scripts/check-work-docs.py --links $(git ls-files ':(glob)README.md' ':( | main 단계 | (가)의 `# main push` 줄과 `run-compose-runtime-smoke.sh`·`check-docs.py`(자기 시험 포함), (나)에서 main `push`로 켜지는 것 | | 라운드 끝 | 위 둘 전부와 (가)의 `# 태그` 두 줄 | -- 태그 두 줄(`releaseCheck`)은 합친 트리에서 provenance와 공개 경로 스냅숏이 깨지지 않았는지만 본다. `release.yml`의 다른 job(web·websocket·gRPC·httpclient·jpa·fileserver release gate, 이미지)은 릴리스 전에만 돈다([operate.md](../operate.md) 4.3절). 결과 표에 "태그 단계 — 라운드 끝 아님"으로 적는다. +- 태그 두 줄(`releaseCheck`)은 합친 트리에서 provenance와 공개 경로 스냅숏이 깨지지 않았는지만 본다. `release.yml`의 다른 job(web·websocket·httpclient·jpa·fileserver release gate, 이미지)은 릴리스 전에만 돈다([operate.md](../operate.md) 4.3절). 결과 표에 "태그 단계 — 라운드 끝 아님"으로 적는다. **실제로 돌았음을 보이기.** 새 detached worktree에서 시작하고 모든 Gradle 명령에 `--no-build-cache`를 붙인다. workflow 명령에 그 옵션이 없어도(예: `tasks --group verification`) 증거 실행에는 붙인다. 바뀌는 것은 캐시 사용뿐이라 판정은 같다. 로그마다 `grep -c 'FROM-CACHE' <로그>`가 0이어야 한다. UP-TO-DATE는 같은 worktree에서 앞 명령이 만든 출력일 때만 받아들인다(4절). `--rerun`은 바로 앞 태스크 하나에만 걸려 `ci` 같은 집계 태스크의 증거가 되지 않는다. @@ -102,18 +101,13 @@ cd src # PR: ci-quality-gates.yml ./gradlew :ci :verifyDependencyLocks --warning-mode=fail --no-build-cache --console=plain ./gradlew :verifyStrictLaneStages --dry-run --console=plain -./gradlew -p platforms/optional-build ci --no-build-cache --console=plain -./gradlew -p platforms/optional-build :verifyStrictLaneStages --dry-run --console=plain # main push: integration-main.yml ./gradlew :mainCheck --continue --warning-mode=fail --no-build-cache --console=plain ./gradlew :integrationCheck --continue --no-build-cache --console=plain ./gradlew :performanceCheck --continue --no-build-cache --console=plain -./gradlew -p platforms/optional-build performanceCheck --continue --no-build-cache --console=plain -./gradlew -p platforms/optional-build integrationCheck --no-build-cache --console=plain ./gradlew :adapter:outbound:httpclient:test -Phttp3.tests.enabled=true --no-build-cache --console=plain # 실험 job, 실패해도 workflow는 통과 # 태그: release.yml (CI는 GITHUB_SHA로 커밋을 받는다. 손으로 돌릴 때는 -PgitRevision) ./gradlew :releaseCheck -PgitRevision="$(git rev-parse HEAD)" --no-build-cache --console=plain -./gradlew -p platforms/optional-build releaseCheck -PgitRevision="$(git rev-parse HEAD)" --no-build-cache --console=plain cd .. bash scripts/verify-compose-profile-contracts.sh python3 scripts/check-repo-layout.py @@ -141,7 +135,6 @@ bash scripts/run-compose-runtime-smoke.sh --matrix src/app-bootstrap/compose-lan | job | 로컬에서 | 대체가 못 보는 것 | | --- | --- | --- | | `link-check.yml`(lychee) | 2절 끝의 같은 범위 상대 링크 검사. desktop에 lychee 공식 이미지가 이미 있으면 그 이미지로 같은 범위를 돌린다 | 외부 URL | -| `ci-quality-gates.yml` `grpc-proto-buf`(`buf lint`·`buf breaking`) | buf나 desktop에 이미 있는 buf 공식 이미지가 있으면 job의 `run` 줄 그대로. 없으면 못 돌림으로 적는다. diff에 `.proto`·`buf*.yaml`이 없으면 "해당 없음 — proto 변경 없음" | 전부 | | `dependency-vulnerability.yml` `dependency-review`·`dependency-submission` | GitHub에서만 돈다. diff에 lockfile·`src/gradle/libs.versions.toml` 변경이 없으면 "해당 없음", 있으면 PR 결과를 보고 남은 문제로 적는다 | 전부 | | `dependency-vulnerability.yml` `trivy-fs` | 이미 설치된 trivy나 desktop에 이미 있는 trivy 공식 이미지가 있으면 job의 검사 줄 그대로. workflow가 쓰는 버전이 없으면 있는 버전으로 기준 트리와 이번 트리를 같은 DB로 돌려 새로 생긴 걸림만 이번 변경 몫으로 본다. job이 trivy를 내려받아 설치하는 줄은 따라 하지 않는다([operate.md](../operate.md) 4.1절). 없으면 못 돌림 | 전부(못 돌렸을 때) | @@ -206,7 +199,6 @@ for k in tests skipped failures errors; do cat $(find "$x" -name 'TEST-*.xml') | | 거짓 통과 모양 | 지금의 장치 | | --- | --- | | 어떤 workflow도 돌리지 않는 lane | `verifyStrictLaneStages --dry-run`(PR) | -| optional 빌드를 보지 않음 | optional 빌드도 같은 검사 | | 실패를 막지 못하는 workflow 명령을 실행으로 셈(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) | `src/build-logic/AGENTS.md` 「`verifyStrictLaneStages`가 세는 명령」 | | lane 정책을 바꿨는데 캐시가 옛 결과로 통과 | lane 정책 값을 Test 입력으로 | | 게이트 밖에서 실패한 채 방치된 검사 | `testQualityCheck`(`mainCheck`) | diff --git a/docs/work/reference/related-repos.md b/docs/work/reference/related-repos.md new file mode 100644 index 00000000..af907a42 --- /dev/null +++ b/docs/work/reference/related-repos.md @@ -0,0 +1,39 @@ +# 관련 저장소 — 템플릿 밖에서 관리하는 라이브러리 + +프로젝트 계층이 아닌 라이브러리는 이 repo에 두지 않는다(소유자 결정 2026-11-07, [decisions.md](decisions.md) 「라이브러리 repo」). 라이브러리마다 별도 repo에서 고치고 Gitea Packages에 버전으로 배포한다. 이 문서는 그 목록과, 템플릿에서 그 라이브러리를 다루는 법이다. 설계 근거는 design-docs `repo-structure/05-library-repos.md`다. + +## 1. 목록 + +| repo | 무엇 | Maven group | 카탈로그 칸 | 쓰는 leaf | +| --- | --- | --- | --- | --- | +| [grpc-library](https://git.learn.hyeonworks.com/donghyeon.kang/grpc-library) | gRPC 플랫폼(Stable 7, advanced 2) | `dev.cakit.grpc` | 없음(채택 전) | 없음. `adapter:inbound:grpc`는 `io.grpc`를 직접 쓴다. 채택은 별도 결정이다 | +| `messaging-library` | 메시징 제품 | `dev.cakit.messaging` | (옮긴 뒤 `messagingLibrary`) | 아직 `src/platforms/messaging`에 있다. 다음 분리 작업에서 옮긴다 | + +고치는 법·게이트·릴리스는 각 repo의 `docs/work/`다. 이 repo의 매뉴얼은 위치만 가리킨다. + +## 2. 라이브러리를 고칠 때 + +- 템플릿 안에서 라이브러리 코드를 고치지 않는다. 라이브러리 repo에서 고치고 릴리스한다. +- 템플릿 변경 때문에 라이브러리를 고쳐야 하면 브랜치를 둘 만들고, 템플릿에서 명령 줄로만 끼워 같이 시험한다. + + ```bash + ./gradlew --include-build ../grpc-library <태스크> + ``` + + 그 상태로 lockfile을 쓰거나 커밋하지 않는다. +- 병합 순서는 하나다: 라이브러리 PR 병합 → 태그·릴리스 → 템플릿 PR에서 버전을 올리고 lockfile을 다시 쓴다 → 템플릿 병합. +- 라이브러리가 끌고 온 취약 의존성은 템플릿에서 먼저 덮어 막고(Boot 버전이나 카탈로그 `pinned-*`), 라이브러리 repo에 수정을 남긴다. + +## 3. 템플릿이 라이브러리 버전을 올릴 때 + +라이브러리를 카탈로그로 받는 leaf가 생긴 뒤의 절차다(지금은 없다). + +1. `src/gradle/libs.versions.toml`의 라이브러리 버전 칸을 바꾼다. +2. desktop에서 `./gradlew resolveAndLockAll --write-locks` 뒤 `verifyDependencyLocks`. +3. 쓰는 leaf의 `check`와 `architectureCheck`, 그 leaf의 lane. +4. 라이브러리 `CHANGELOG.md`에서 그 사이 버전의 깨지는 변경을 읽는다. MAJOR면 `docs/upgrade/`에 행을 더하고 커밋 제목에 `!`. +5. 커밋 제목 예: `build(deps): gRPC 라이브러리를 1.1.0으로 올린다`. + +## 4. 받는 법(처음 채택할 때) + +`src/settings.gradle`의 저장소 선언에 Gitea Maven 저장소를 `exclusiveContent`로 더한다. `dev.cakit` group은 그 저장소에서만, 나머지는 Maven Central에서만 찾는다. 선언 예는 라이브러리 repo README 「받는 법」이다. 공개 owner라 읽기 토큰은 필요 없다. diff --git a/docs/work/reference/review-criteria.md b/docs/work/reference/review-criteria.md index f72f5daf..20e92b6d 100644 --- a/docs/work/reference/review-criteria.md +++ b/docs/work/reference/review-criteria.md @@ -139,7 +139,7 @@ | DB 오류·경쟁 | `PersistenceExceptionTranslator`, `@Version`, 트랜잭션 마감 | | 메시지 중복·역순 | outbox relay, inbox 재전달, aggregate 순서 번호 | | 신·구 버전 공존 | 마이그레이션 잠금, 배포 중 섞인 인스턴스 | -| 여러 서버의 작업 실행 | 알림 정산 job claim, gRPC ledger claim | +| 여러 서버의 작업 실행 | 알림 정산 job claim, 멱등성 실행 lease | | 다른 사용자 리소스 접근 | 파일 서버 소유자 검사, durable operation 소유자·tenant 검사 | | 큰 입력·목록 조회 | 파일 서버 업로드 크기 한도, GraphQL 복잡도, JSON 아닌 본문 | | 종료·재시작 | relay·platform 종료 순서, 종료 시간 예산 | @@ -201,7 +201,8 @@ RED가 증거가 되려면: 실패 메시지가 그 결함을 말한다. 머신 - 새 업무 기능은 계층 leaf 안의 패키지가 기본이다(`docs/manual/03-placement.md`). - 템플릿 패키지 목록은 `src/application-core/README.md` 「패키지 소유 (Package ownership)」 표 하나가 정본이다. 템플릿에 패키지를 더하면 같은 변경에서 표에 넣는다. - capability는 자기 `AutoConfiguration.imports`로 켜진다. `app-bootstrap`은 capability 이름·스위치 목록·scan 정규식을 갖지 않는다. -- vendored family(`messaging:*`, 같은 방식의 `grpc:*`)는 `domain-core`·`application-core`·`shared-contract`에 의존하지 않는다. 그래서 남는 복사본은 이유를 family `AGENTS.md`에 적고, 값이 같아야 하면 대조 테스트를 둔다. +- 다른 경계(다른 leaf, 다른 빌드, 다른 repo가 될 수 있는 폴더)의 파일을 경로(`../../../`)로 읽는 빌드 스크립트·테스트는 결함 후보다. 그 경계가 옮겨 가면 조용히 깨진다. gRPC 라이브러리를 옮길 때 이런 결합이 다섯 곳 나왔다(design-docs `repo-structure/05-library-repos.md` 4.6절). +- vendored family(`messaging:*`)는 `domain-core`·`application-core`·`shared-contract`에 의존하지 않는다. 그래서 남는 복사본은 이유를 family `AGENTS.md`에 적고, 값이 같아야 하면 대조 테스트를 둔다. - source set은 runtime·classpath·외부 인프라·JVM 옵션·실행 비용 중 하나가 다를 때만 나눈다. 공유 테스트 코드는 `src/testFixtures/java`다(`docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md`). - 마이그레이션은 저장소마다 자기 디렉터리와 history table을 가진다. 번호는 스트림 안의 순번이다. 어딘가에 적용된 파일은 고치지 않는다(`src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256`이 해시를 고정한다). - 문서 위치 규칙은 `docs/README.md`가 정본이다. diff --git a/scripts/check-repo-layout.py b/scripts/check-repo-layout.py index 41a5e414..8c6e3412 100755 --- a/scripts/check-repo-layout.py +++ b/scripts/check-repo-layout.py @@ -71,7 +71,7 @@ SRC_ALLOWED = { "composition": "조립(Clean Architecture의 Main)", "app-bootstrap": "조립 루트", # 들여온 제품 - "platforms": "들여온 제품(messaging, grpc, grpc-advanced)과 optional 빌드", + "platforms": "들여온 제품(messaging). gRPC는 2026-11-08 별도 repo grpc-library로", # Gradle 루트 표준 "build-logic": "빌드 규칙(included build)", "config": "빌드 전체 도구 설정(registry, checkstyle, spotbugs, 테스트 이미지)", diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index 23e16504..9d427c57 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -74,7 +74,7 @@ executor, 서버 deadline 없음, 연결 수명 무제한이다. 어댑터 서 - **값이 두 곳에 있는 이유.** 03-09 는 (a) 어댑터가 같은 이름·값을 자기 설정으로 노출, (b) 어댑터가 플랫폼 `GrpcServerProfile` 을 받음(registry edge 추가), (c) 현상 유지 중 (a)를 골랐다. 두 스택 분리(X1-#10)를 건드리지 않기 위해서다. 어댑터는 플랫폼 타입을 import 할 수 없어(registry - edge 없음, 플랫폼은 `optional-platforms` 별도 빌드) 상수를 직접 비교하는 테스트는 만들 수 없다. + edge 없음, 플랫폼은 2026-11-08부터 별도 repo `grpc-library`) 상수를 직접 비교하는 테스트는 만들 수 없다. 대신 `GrpcSafeActivationTest.transportBoundDefaultsMatchTheVendoredPlatformDefaults` 가 위 표의 플랫폼 값을 literal 로 고정한다. 플랫폼 값을 바꾸면 이 표와 그 테스트를 같이 바꾼다. - **duration 순서 검증.** `keep-alive-timeout < keep-alive-time`, `permit-keep-alive-time <= diff --git a/src/adapter/outbound/persistence-fileserver/build.gradle b/src/adapter/outbound/persistence-fileserver/build.gradle index 4ec73236..c9ed12d5 100644 --- a/src/adapter/outbound/persistence-fileserver/build.gradle +++ b/src/adapter/outbound/persistence-fileserver/build.gradle @@ -46,6 +46,6 @@ apiSurface { adopterBaseline = rootProject.file('../docs/architecture/persistence-fileserver-adopter-api-surface.txt') adopterSources = fileTree(rootProject.projectDir) { include '*/**/src/main/java/**/*.java' - exclude '**/build/**', 'adapter/outbound/persistence-fileserver/**', 'build-logic/**', 'platforms/optional-build/**' + exclude '**/build/**', 'adapter/outbound/persistence-fileserver/**', 'build-logic/**' } } diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index b5561784..6ef7a85e 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -357,7 +357,7 @@ apiSurface { include '*/**/src/main/java/**/*.java' exclude '**/build/**', 'adapter/outbound/persistence-jpa/**', 'adapter/outbound/persistence-fileserver/**', 'adapter/outbound/persistence-notification/**', - 'build-logic/**', 'platforms/optional-build/**' + 'build-logic/**' } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java index 87c09f27..3d7f510e 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java @@ -15,8 +15,8 @@ import org.junit.jupiter.api.io.TempDir; /** * One definition of a versioned migration for every check that walks a tree (re-review 2026-11-03 * round 3, RR3-02-03): the operating trees' checks once skipped {@code V22_1__} while the sample's - * counted it. The gRPC ledger's list in the optional build is compiled from this same source - * (README 12, r6-b; r9). + * counted it. The grpc-library repository's ledger lanes keep a copy of this source (README 12, + * r6-b; r9). */ class VersionedMigrationFilesTest { diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java index f1a0f843..33351a10 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java @@ -36,11 +36,11 @@ import java.util.regex.Pattern; * Flyway's default the lock's own open transaction is one of those, and the deploy never ends * (re-review 2026-11-03 round 6, RR6-03-01 and RR6-03-05). * - *

The gRPC ledger's lane uses it too. It lives in the optional build, which cannot depend on - * this testkit, so {@code grpc-operation-ledger-jpa} compiles this file and {@link - * MigrationResource} from here into its integration-test sources at build time (its {@code - * build.gradle}, {@code sharedMigrationFileSources}; round 7, RR7-03-01). Hence the rule for both - * files: the JDK only, nothing else from this testkit. + *

The gRPC ledger's lane uses it too. Since 2026-11-08 that lane lives in the separate + * grpc-library repository, which keeps a copy of this file and {@link MigrationResource} in its + * integration-test sources (until then its build compiled them from here; round 7, RR7-03-01). This + * file is the original: a fix here is copied there by hand. Hence the rule for both files: the JDK + * only, nothing else from this testkit. */ public final class ConcurrentIndexMigrationInspector { diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java index 6251b391..f4846006 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java @@ -5,7 +5,7 @@ import java.util.Objects; /** * One migration script as the inspector sees it (design §32). * - *

The gRPC ledger's lane in the optional build compiles this file with {@link + *

The grpc-library repository keeps a copy of this file with {@link * ConcurrentIndexMigrationInspector} (see there), so it keeps to the JDK only. * * @param name the versioned script name, e.g. {@code V42__order_index.sql} diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java index ba08ff92..7fd4550f 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java @@ -24,11 +24,11 @@ import java.util.stream.Stream; * V22_1__} while the sample's counted it, so a decimal version in an operating tree was neither * pinned nor held to the lock-wait rule (re-review 2026-11-03 round 3, RR3-02-03). * - *

The gRPC ledger's lanes use it too. They live in the optional build, which cannot depend on - * this testkit, so {@code grpc-operation-ledger-jpa} compiles this one file from here into its - * integration-test sources at build time (its {@code build.gradle}, {@code - * sharedMigrationFileSources}) instead of keeping a copy that could drift (re-review README 12, - * r6-b; r9). Hence the rule for this file: the JDK only, nothing else from this testkit. + *

The gRPC ledger's lanes use it too. Since 2026-11-08 they live in the separate grpc-library + * repository, which keeps a copy of this file in its integration-test sources (until then its build + * compiled this one from here; re-review README 12, r6-b; r9). This file is the original: a fix + * here is copied there by hand. Hence the rule for this file: the JDK only, nothing else from this + * testkit. */ public final class VersionedMigrationFiles { diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index e2a7b6bd..05cb31fb 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -124,8 +124,7 @@ sourceSets { // Every capability a service can select — the commented runtimeOnly lines below — listed once. // Three consumers read it — the environment contract's metadata classpath (verifyEnvKeys, below) // and these two: the whole-repository ArchUnit import (spec §7: the architecture suite sees -// every module of this build, the shipped runtime only the selected ones; the -// optional-platforms build is held by its own Gradle direction gate instead) and the qualification artifact the +// every module of this build, the shipped runtime only the selected ones) and the qualification artifact the // Compose lanes boot (qualificationBootJar, below). None of them 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. @@ -181,10 +180,6 @@ dependencies { integrationTestImplementation project(':composition:service-runtime') capabilityProjects.each { architectureTestRuntimeOnly project(it) } - // What this import does NOT see: the optional-platforms build (`grpc:*`, `grpc-advanced:*`). - // It is a separate Gradle build, so its classes cannot be on this classpath; its registered - // leaves are held by the Gradle direction gate (`-p platforms/optional-build ci` runs - // verifyCleanArchitectureDependencies), which is the whole of what the owner decided it needs. // The capability integration lane selects Fileserver and object storage together, as a service // would, and turns off whichever one a test is not about. diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java index 38e4b325..bcf8e25e 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java @@ -362,30 +362,6 @@ class DeveloperExperienceContractTest { .noneMatch(step -> step instanceof Map map && map.containsKey("uses")); } - @Test - @Tag("repository-contract") - void everyOptionalPlatformIntegrationLaneHasAnExecutingWorkflowCaller() throws IOException { - // `grpc-operation-ledger-jpa` declares a Testcontainers PostgreSQL lane that certifies the - // atomic claim durable mutation idempotency rests on. It was registered in `strictTestLanes`, - // fails closed, and ran nowhere: the optional build's `ci` reaches `checkAll`, `qualityCheck` - // and the dependency verifier, and none of those runs a lane whose category is INTEGRATION. - // A lane nobody runs is not coverage, so both halves are pinned here — the aggregate that - // covers the category, and the workflow that executes the aggregate. - assertThat(read("src/platforms/optional-build/build.gradle")) - .as("the optional platform build must aggregate its integration-category lanes") - .contains("tasks.register('integrationCheck')") - .contains(":integrationTestLaneCheck"); - - assertThat(read("src/platforms/grpc/grpc-operation-ledger-jpa/build.gradle")) - .as("the operation ledger lane this contract protects must still be declared") - .contains("lane('integrationTest')") - .contains("integration()"); - - assertThat(read(".github/workflows/integration-main.yml")) - .as("a workflow must actually execute the optional platform integration aggregate") - .contains("./gradlew -p platforms/optional-build integrationCheck"); - } - @Test @Tag("repository-contract") @DisplayName("compose 종료 유예 시간은 웹 drain, async 대기, preStop, 여유를 모두 더한 값 이상이다") diff --git a/src/build-logic/AGENTS.md b/src/build-logic/AGENTS.md index 76de3ad1..d5f1fa86 100644 --- a/src/build-logic/AGENTS.md +++ b/src/build-logic/AGENTS.md @@ -25,7 +25,7 @@ registry, settings, build-logic, 루트 라이프사이클이 정하는 것을 ## `verifyStrictLaneStages`가 세는 명령 -`verifyStrictLaneStages --dry-run`(PR 게이트)은 그 빌드에서 `explicitOnly`가 아닌 strict lane이 workflow가 실제로 실행하는 단계(main 빌드: `ci`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`, optional-platforms 빌드: `-p platforms/optional-build`로 부르는 `ci`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 줄 때문에 옵션을 별개 명령으로 떼어 내지 않는지 검사한다. 두 빌드가 각자 검사를 돌린다. `-x`로 뺀 lane(Gradle처럼 축약 이름도 맞춰 본다)은 덮이지 않는다. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-m`·`-v`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 `-qm`·`-qv` 포함)과 Gradle이 거부하는 짧은 옵션 묶음(`-mx`), 다른 빌드를 실행하는 명령은 세지 않는다. 그 밖에 세지 않는 명령은 이유가 셋이다. +`verifyStrictLaneStages --dry-run`(PR 게이트)은 그 빌드에서 `explicitOnly`가 아닌 strict lane이 workflow가 실제로 실행하는 단계(`ci`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 줄 때문에 옵션을 별개 명령으로 떼어 내지 않는지 검사한다. `-x`로 뺀 lane(Gradle처럼 축약 이름도 맞춰 본다)은 덮이지 않는다. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-m`·`-v`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 `-qm`·`-qv` 포함)과 Gradle이 거부하는 짧은 옵션 묶음(`-mx`), 다른 빌드를 실행하는 명령은 세지 않는다. 그 밖에 세지 않는 명령은 이유가 셋이다. 1. 실패해도 단계가 실패하지 않을 수 있다: `|| exit <0 아닌 값>` 밖의 `||`(`|| true` 등), pipefail 없는 파이프 왼쪽, `!`, `&`, `if`·`while` 조건, 스크립트 마지막이 아닌 `&&` 목록의 앞쪽, `set +e` 뒤, `exit 0` 하는 `EXIT`·`ERR` trap 뒤, `continue-on-error`. 2. 돌지 않을 수 있다: `||` 뒤, 마지막이 아닌 `&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec`·`set -n` 뒤, 조건부이거나 부른 함수 안의 `exit 0`(인자 없는 `exit`, 값을 모르는 `exit` 포함)·`exec`·`set -n` 뒤, 상태 함수(`always()`·`success()`·`!cancelled()`)가 아닌 `if:` 아래, 요청으로만 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment` 등), `paths`·`paths-ignore` 필터가 붙은 change trigger로만 시작하는 workflow(그 경로 밖 변경에는 돌지 않는다), 태그 push(`branches` 없는 `tags`)나 `release`로만 시작하는 workflow(`releaseCheck` 밖의 단계), 세는 job이 부르지 않는 `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job. diff --git a/src/build-logic/README.md b/src/build-logic/README.md index cd9fe39b..71cf803e 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -13,9 +13,9 @@ capability를 가진 leaf의 시험이고, 그 시험이 읽는 파일은 그 | `ca.java-conventions` | Java toolchain·컴파일러 기준, 의존성 잠금, Mockito 시험 agent, leaf별 `mainCheck` lifecycle, leaf 버전(릴리스 버전만)과 `sourceRevision`(`JavaConventionsPlugin.sourceRevision`. 루트 `verifyReleaseProvenance`가 검사하는 것도 이것이다) | | `ca.quality-conventions` | Java leaf가 같이 쓰는 Spotless, Checkstyle, Error Prone, SpotBugs·FindSecBugs 배선 | | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | 평범한 라이브러리와 Spring 라이브러리를 위한 Java·품질 규약의 leaf 단위 조합 | -| `ca.platform-module` / `ca.grpc-platform-module` | 들여온 플랫폼 leaf(`messaging:*`, `grpc:*`, `grpc-advanced:*`)가 무엇인가: `java-library`, 그리고 원래 gRPC BOM을 쓰던 leaf에는 그 BOM | +| `ca.platform-module` | 들여온 플랫폼 leaf(`messaging:*`)가 무엇인가: `java-library`. gRPC 플랫폼과 그 BOM 규약(`ca.grpc-platform-module`)은 2026-11-08에 별도 repo `grpc-library`로 옮겼다 | | `ca.strict-test-lane` | 「이름 댄 시험이 돌았고 건너뛴 것이 없다」를 보는 유일한 장치: tag·이름·자기 source set으로 고른 `Test` lane이 아무것도 실행하지 않거나, `requires` 클래스를 빠뜨리거나, (`rejectSkipped`이면) 무엇이든 건너뛰면 실패한다. `performance()` lane은 언제나 건너뛰기를 거절하고 `performance.assertions.enabled=true`로 돈다. 빌드(`-P`, `GRADLE_OPTS`)나 lane이 다른 값을 넣으면 시험이 돌기 전에 실패한다. `mainStage()`는 tag로 고른 lane을 `test`에서 빼 leaf의 `mainCheck`로 옮긴다. `explicitOnly(reason)`는 바깥 입력이 필요한 lane을 모든 묶음 태스크에서 빼고, 묶음 태스크가 그 이유를 출력한다. 시험 source set을 더 두려면 leaf에 Gradle `jvm-test-suite` suite로 선언한다(`testing { suites { … } }`). suite 이름을 딴 lane은 그 suite 자신의 `Test` 태스크를 엄격하게 만들고, `ca.java-conventions`는 모든 suite에 BOM의 JUnit을 준다 | -| `ca.strict-lane-stages` (strict lane이 있는 각 빌드의 루트: 주 빌드와 optional-platforms) | lane 장치의 나머지 절반: `verifyStrictLaneStages --dry-run`은 그 빌드의 `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 선언된 단계 어느 것의 태스크 계획에도 없거나, 선언된 단계를 실행하는 workflow가 없으면 실패한다. workflow는 함께 읽고(`WorkflowGradleInvocations.readAll`. 그래서 재사용 workflow는 그것을 부르는 쪽으로 판정한다) `run:` 스크립트는 bash로 파싱한다(`ShellScript`: 따옴표, 주석, heredoc 본문, 치환, 복합 명령을 셸이 읽듯 읽는다. 그래서 heredoc이나 문자열 안의 `cd`는 데이터다). Gradle이 태스크를 하나도 돌리지 않는 명령은 세지 않는다 — `--dry-run`/`-m`(`-qm` 같은 묶음 안도), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground`(`-qv` 같은 묶음 안도) — Gradle이 거절하는 명령도 세지 않는다: 뒤 글자가 값을 받는 짧은 옵션 묶음(`-mx`: 묶음에서는 첫 글자만 값을 받는다), 값을 받지 않는 옵션에 준 값(`-m=yes`). 읽는 방식은 Gradle 9.0의 파서를 따른다. `GradleCommandLineTest`는 옵션 표를 build-logic을 돌리는 Gradle의 `--help`와 맞춘다 — 옵션을 더하는 업그레이드는(9.2가 `--task-graph`를 더하듯) 그 옵션을 자리에 넣기 전까지 실패한다 — 그리고 `--stop`과 `--foreground`를 뺀 태스크 없는 옵션마다 launcher를 돌린다(둘은 Gradle `BuildActionsFactory`에서 빌드가 아니라 daemon 동작을 돌려준다). 어떤 옵션이 값을 받는지는 round 9에 9.0.0으로 탐침했고 다시 돌리지 않는다. 다른 빌드를 위한 명령도 세지 않는다(명령이 시작하는 빌드는 그 step의 `working-directory`, 또는 job이나 workflow의 `defaults.run.working-directory`에서 시작해, 같은 `run:` 셸이 그 앞에서 반드시 돌린 `cd <리터럴 상대 경로>`마다 옮기고 — 혼자 있는 목록이거나 같은 `&&` 목록에서 그 명령 앞에 있을 때 — 그다음 `-p`로 이은 곳이다. 플러그인은 이 빌드 자신의 디렉터리를 `.github/workflows`를 가진 저장소 아래 어디에 있는지로 읽는다). 세지 않는 그 밖의 명령은 모두 세 이유 중 하나를 댄다. **실패해도 step이 실패하지 않을 수 있다**: `\|\| true`, `\|\| :`, `\|\| exit <0 아닌 값>`이 아닌 모든 `\|\|`, `pipefail` 없는 pipe의 왼쪽(`shell: bash`나 최상위 `set -o pipefail`이면 켜진다), `!`, `&`, `if`/`while` 조건, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 앞부분, `set +e` 뒤, `EXIT`나 `ERR` 동작이 상태 0으로 `exit`할 수 있는 `trap` 뒤(`EXIT` trap 안의 맨 `exit`는 상태를 지키지만 `ERR` trap 안에서는 아니다), `continue-on-error`. **돌지 않을 수 있다**: `\|\|` 뒤, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 뒤, `if`/`while`/`for`/`case` 안이나 함수 본문 안, 최상위 `exit`·`exec `·`set -n` 뒤, 다른 곳 — 복합 명령, and-or 목록, 스크립트가 부르는 함수 — 에서 스크립트를 상태 0으로 끝낼 수 있는 것(`exit 0`, `\|\|` 바로 뒤가 아닌 맨 `exit`, `exit "$code"`), 스크립트를 바꿔치는 것, 명령 실행을 멈추는 것(`set -o noexec`) 뒤, `always()`/`success()`/`!cancelled()`가 아닌 `if:` 아래, 누가 또는 무엇이 요청해야만 시작하는 이벤트(`workflow_dispatch`, `repository_dispatch`, `issue_comment`, `types: [labeled]`인 pull request, `workflow_run`, …. `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule`, `release`는 센다)로만 시작하는 workflow 안, 변경 흐름 트리거가 모두 `paths`나 `paths-ignore` 필터를 가진 workflow 안(그 경로 밖의 변경은 workflow를 시작하지 않는다. 소유자 결정 2026-11-06), 요청이나 경로 필터 없이 릴리스 흐름에서만 시작하는 workflow 안의 `:releaseCheck`가 아닌 단계 — 릴리스 흐름은 `release`, 또는 `tags`/`tags-ignore`가 있고 `branches`/`branches-ignore`가 없는 `push`로, 브랜치 push로는 시작하지 않는다(소유자 결정 2026-11-07. `:releaseCheck`가 태그 전용 단계다) — 센 job 어느 것도 `uses: ./.github/workflows/`로 부르지 않는 재사용(`workflow_call`만 있는) workflow 안, 그리고 그런 `if:`나 `continue-on-error`를 가진 job을 직접 또는 다른 job을 거쳐 `needs`하는 job 안(자기 `if:`가 `always()`나 `!cancelled()`이면 예외). **이 검사가 읽지 않는다**(실패하면 step이 실패하지만, 일부러 거짓 실패로 둔다): `\|\| exit 1`, `\|\| { …; exit 1; }`, `{ }`나 `( )` 안, `$( )`, `bash -c`, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), 읽는 쪽이 따라가지 않는 디렉터리 이동 뒤(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`/`popd`, `builtin cd`, `eval`/`source`, 복합 명령이나 함수 본문 안의 `cd`, `\|\|`로 이은 것, pipe나 background로 돌린 것, 다른 명령과 같은 `&&` 목록에 있는 `cd`의 뒤 줄 — 짐작하지 않는다), `shell:`이 `bash`나 `sh`가 아닌 step, `runs-on`이 Windows runner일 수 있는 job에서 `shell:`이 없는 step(기본 셸이 `pwsh`다. Windows label, `${{ matrix.os }}` 같은 표현식, `linux`나 `macos`가 없는 self-hosted label 집합. Linux·macOS runner의 기본은 `bash -e`, `container:` job의 기본은 `sh -e`이고 둘을 같이 읽는다). step을 실패시키는 `exit` — `exit 1`, `cmd \|\| exit` — 와 부르지 않는 함수, `( )` subshell, `$( )` 안의 `exit`는 그 뒤의 명령이 세지는 것을 막지 않는다. 실패 메시지는 단계 이름을 대지만 그 단계를 실행하지 않는 모든 명령을 그 이유나 그것이 시작하는 다른 빌드와 함께 대고, 단계를 혼자 있는 줄의 `./gradlew`로 돌리라고 말한다. 명령이 `-x`로 뺀 lane은 덮인 것이 아니다 — Gradle이 태스크·프로젝트 이름을 맞추는 방식(약어 포함)으로 맞춘다(`TaskSelectors`, Gradle 내부 `NameMatcher`의 사본). `uses:` step의 `run:` 입력은 명령이 아니다. 계획은 Gradle 자신의 것이다. workflow는 YAML folding을 적용해 `run:` step을 읽는다(review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, `cd`에 대한 소유자 결정 2026-11-04, round 9의 RR5-02-01/02/03, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01, 릴리스 흐름에 대한 소유자 결정 2026-11-07) | +| `ca.strict-lane-stages` (주 빌드의 루트) | lane 장치의 나머지 절반: `verifyStrictLaneStages --dry-run`은 그 빌드의 `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 선언된 단계 어느 것의 태스크 계획에도 없거나, 선언된 단계를 실행하는 workflow가 없으면 실패한다. workflow는 함께 읽고(`WorkflowGradleInvocations.readAll`. 그래서 재사용 workflow는 그것을 부르는 쪽으로 판정한다) `run:` 스크립트는 bash로 파싱한다(`ShellScript`: 따옴표, 주석, heredoc 본문, 치환, 복합 명령을 셸이 읽듯 읽는다. 그래서 heredoc이나 문자열 안의 `cd`는 데이터다). Gradle이 태스크를 하나도 돌리지 않는 명령은 세지 않는다 — `--dry-run`/`-m`(`-qm` 같은 묶음 안도), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground`(`-qv` 같은 묶음 안도) — Gradle이 거절하는 명령도 세지 않는다: 뒤 글자가 값을 받는 짧은 옵션 묶음(`-mx`: 묶음에서는 첫 글자만 값을 받는다), 값을 받지 않는 옵션에 준 값(`-m=yes`). 읽는 방식은 Gradle 9.0의 파서를 따른다. `GradleCommandLineTest`는 옵션 표를 build-logic을 돌리는 Gradle의 `--help`와 맞춘다 — 옵션을 더하는 업그레이드는(9.2가 `--task-graph`를 더하듯) 그 옵션을 자리에 넣기 전까지 실패한다 — 그리고 `--stop`과 `--foreground`를 뺀 태스크 없는 옵션마다 launcher를 돌린다(둘은 Gradle `BuildActionsFactory`에서 빌드가 아니라 daemon 동작을 돌려준다). 어떤 옵션이 값을 받는지는 round 9에 9.0.0으로 탐침했고 다시 돌리지 않는다. 다른 빌드를 위한 명령도 세지 않는다(명령이 시작하는 빌드는 그 step의 `working-directory`, 또는 job이나 workflow의 `defaults.run.working-directory`에서 시작해, 같은 `run:` 셸이 그 앞에서 반드시 돌린 `cd <리터럴 상대 경로>`마다 옮기고 — 혼자 있는 목록이거나 같은 `&&` 목록에서 그 명령 앞에 있을 때 — 그다음 `-p`로 이은 곳이다. 플러그인은 이 빌드 자신의 디렉터리를 `.github/workflows`를 가진 저장소 아래 어디에 있는지로 읽는다). 세지 않는 그 밖의 명령은 모두 세 이유 중 하나를 댄다. **실패해도 step이 실패하지 않을 수 있다**: `\|\| true`, `\|\| :`, `\|\| exit <0 아닌 값>`이 아닌 모든 `\|\|`, `pipefail` 없는 pipe의 왼쪽(`shell: bash`나 최상위 `set -o pipefail`이면 켜진다), `!`, `&`, `if`/`while` 조건, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 앞부분, `set +e` 뒤, `EXIT`나 `ERR` 동작이 상태 0으로 `exit`할 수 있는 `trap` 뒤(`EXIT` trap 안의 맨 `exit`는 상태를 지키지만 `ERR` trap 안에서는 아니다), `continue-on-error`. **돌지 않을 수 있다**: `\|\|` 뒤, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 뒤, `if`/`while`/`for`/`case` 안이나 함수 본문 안, 최상위 `exit`·`exec `·`set -n` 뒤, 다른 곳 — 복합 명령, and-or 목록, 스크립트가 부르는 함수 — 에서 스크립트를 상태 0으로 끝낼 수 있는 것(`exit 0`, `\|\|` 바로 뒤가 아닌 맨 `exit`, `exit "$code"`), 스크립트를 바꿔치는 것, 명령 실행을 멈추는 것(`set -o noexec`) 뒤, `always()`/`success()`/`!cancelled()`가 아닌 `if:` 아래, 누가 또는 무엇이 요청해야만 시작하는 이벤트(`workflow_dispatch`, `repository_dispatch`, `issue_comment`, `types: [labeled]`인 pull request, `workflow_run`, …. `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule`, `release`는 센다)로만 시작하는 workflow 안, 변경 흐름 트리거가 모두 `paths`나 `paths-ignore` 필터를 가진 workflow 안(그 경로 밖의 변경은 workflow를 시작하지 않는다. 소유자 결정 2026-11-06), 요청이나 경로 필터 없이 릴리스 흐름에서만 시작하는 workflow 안의 `:releaseCheck`가 아닌 단계 — 릴리스 흐름은 `release`, 또는 `tags`/`tags-ignore`가 있고 `branches`/`branches-ignore`가 없는 `push`로, 브랜치 push로는 시작하지 않는다(소유자 결정 2026-11-07. `:releaseCheck`가 태그 전용 단계다) — 센 job 어느 것도 `uses: ./.github/workflows/`로 부르지 않는 재사용(`workflow_call`만 있는) workflow 안, 그리고 그런 `if:`나 `continue-on-error`를 가진 job을 직접 또는 다른 job을 거쳐 `needs`하는 job 안(자기 `if:`가 `always()`나 `!cancelled()`이면 예외). **이 검사가 읽지 않는다**(실패하면 step이 실패하지만, 일부러 거짓 실패로 둔다): `\|\| exit 1`, `\|\| { …; exit 1; }`, `{ }`나 `( )` 안, `$( )`, `bash -c`, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), 읽는 쪽이 따라가지 않는 디렉터리 이동 뒤(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`/`popd`, `builtin cd`, `eval`/`source`, 복합 명령이나 함수 본문 안의 `cd`, `\|\|`로 이은 것, pipe나 background로 돌린 것, 다른 명령과 같은 `&&` 목록에 있는 `cd`의 뒤 줄 — 짐작하지 않는다), `shell:`이 `bash`나 `sh`가 아닌 step, `runs-on`이 Windows runner일 수 있는 job에서 `shell:`이 없는 step(기본 셸이 `pwsh`다. Windows label, `${{ matrix.os }}` 같은 표현식, `linux`나 `macos`가 없는 self-hosted label 집합. Linux·macOS runner의 기본은 `bash -e`, `container:` job의 기본은 `sh -e`이고 둘을 같이 읽는다). step을 실패시키는 `exit` — `exit 1`, `cmd \|\| exit` — 와 부르지 않는 함수, `( )` subshell, `$( )` 안의 `exit`는 그 뒤의 명령이 세지는 것을 막지 않는다. 실패 메시지는 단계 이름을 대지만 그 단계를 실행하지 않는 모든 명령을 그 이유나 그것이 시작하는 다른 빌드와 함께 대고, 단계를 혼자 있는 줄의 `./gradlew`로 돌리라고 말한다. 명령이 `-x`로 뺀 lane은 덮인 것이 아니다 — Gradle이 태스크·프로젝트 이름을 맞추는 방식(약어 포함)으로 맞춘다(`TaskSelectors`, Gradle 내부 `NameMatcher`의 사본). `uses:` step의 `run:` 입력은 명령이 아니다. 계획은 Gradle 자신의 것이다. workflow는 YAML folding을 적용해 `run:` step을 읽는다(review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, `cd`에 대한 소유자 결정 2026-11-04, round 9의 RR5-02-01/02/03, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01, 릴리스 흐름에 대한 소유자 결정 2026-11-07) | | `ca.redis-topology-lane` | redis-sdk-topology workflow가 돌리는 Redis topology lane(모드 고르기, `-P` 속성 검증, 모드별 필수 클래스) | | `ca.api-surface` | 읽기 전용 공개 API surface 검증과 따로 둔 갱신 태스크. leaf의 `check`에 배선한다(소유자 결정 20). 다른 leaf의 import를 리뷰한 adopter 부분집합(`adopterBaseline`)에 묶을 수도 있다 | | `ca.config-contract` | app-bootstrap의 `verifyEnvKeys`(지운 build-tools included build에서 옮겼다. 소유자 결정 4가 그 태스크를 app-bootstrap에 둔다) | diff --git a/src/build-logic/build.gradle b/src/build-logic/build.gradle index 1c004fb7..e1a7f4d5 100644 --- a/src/build-logic/build.gradle +++ b/src/build-logic/build.gradle @@ -71,10 +71,6 @@ gradlePlugin { id = 'ca.architecture-registry' implementationClass = 'dev.caskeleton.buildlogic.settings.ArchitectureRegistrySettingsPlugin' } - optionalArchitectureRegistrySettings { - id = 'ca.optional-architecture-registry' - implementationClass = 'dev.caskeleton.buildlogic.settings.OptionalArchitectureRegistrySettingsPlugin' - } javaLibraryConvention { id = 'ca.java-library' implementationClass = 'dev.caskeleton.buildlogic.convention.JavaLibraryConventionPlugin' @@ -95,10 +91,6 @@ gradlePlugin { id = 'ca.config-contract' implementationClass = 'dev.caskeleton.buildlogic.config.ConfigContractPlugin' } - grpcPlatformModuleConvention { - id = 'ca.grpc-platform-module' - implementationClass = 'dev.caskeleton.buildlogic.convention.GrpcPlatformModuleConventionPlugin' - } } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/MainBuild.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/MainBuild.java deleted file mode 100644 index c64083b9..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/MainBuild.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.buildlogic; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import org.gradle.api.GradleException; - -/** - * Where the main build is, seen from any build of this repository. - * - *

The main build is the Gradle root that owns the module registry ({@code - * config/architecture/modules.json}); the repository root is its parent. The optional platform build - * lives inside it ({@code src/platforms/optional-build}), and the code that needs the registry, the - * shared tool configuration or the test image catalog used to reach the main build by taking one - * parent of the optional build's root. That held only while the optional build sat directly under - * the main build; it is found by walking up instead, so the optional build's depth is not a fact - * every caller repeats. - */ -public final class MainBuild { - /** The registry, relative to the main build: what makes a directory the main build. */ - public static final String REGISTRY = "config/architecture/modules.json"; - - private MainBuild() {} - - /** - * The main build's directory: {@code buildRoot} itself or the nearest directory above it that - * holds the module registry. - * - * @param buildRoot the root directory of the build asking (its settings or root project directory) - * @return the canonical main build directory - */ - public static File directory(File buildRoot) { - File registry = nearest(buildRoot, REGISTRY); - if (registry == null) { - throw new GradleException( - "No " + REGISTRY + " at or above " + buildRoot + "; this build is not inside the repository"); - } - return registry.getParentFile().getParentFile().getParentFile(); - } - - /** - * The nearest {@code relativePath} at or above {@code buildRoot}: in the build's own root first, - * then in each parent. A file or a directory; {@code null} when no ancestor has it. - * - * @param buildRoot the root directory of the build asking - * @param relativePath the path to look for, relative to each candidate directory - * @return the canonical path found, or {@code null} - */ - public static File nearest(File buildRoot, String relativePath) { - for (File directory = canonical(buildRoot); - directory != null; - directory = directory.getParentFile()) { - File candidate = new File(directory, relativePath); - if (candidate.exists()) { - return candidate; - } - } - return null; - } - - /** - * The repository root: the main build's parent. - * - * @param buildRoot the root directory of the build asking - * @return the canonical repository root - */ - public static File repositoryRoot(File buildRoot) { - return directory(buildRoot).getParentFile(); - } - - private static File canonical(File file) { - try { - return file.getCanonicalFile(); - } catch (IOException exception) { - throw new UncheckedIOException("cannot resolve " + file, exception); - } - } -} 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 a917abb6..47d2ebb1 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 @@ -108,7 +108,17 @@ public record ModuleRegistry(List modules, File source) { String id = requireNonBlankText(module, "id", index); String gradlePath = requireNonBlankText(module, "gradle_path", index); String sourcePath = requireNonBlankText(module, "source_path", index); - String buildName = module.has("build") ? requireNonBlankText(module, "build", id) : "main"; + // Every module belongs to the main build. The only other build (the optional gRPC platform + // build) moved to the grpc-library repository on 2026-11-08, and a row naming any build but + // this one would be included by no settings and checked by no direction gate while ci stays + // green, so the field is refused rather than read. + if (module.has("build")) { + throw new IllegalStateException( + "Module registry entry '" + + id + + "' has a 'build' field; every module belongs to the main build, so remove it."); + } + String buildName = "main"; List allowedDependencies = requireStringList(module.get("allowed_dependencies"), id, "allowed_dependencies"); @@ -192,7 +202,7 @@ public record ModuleRegistry(List modules, File source) { *

The settings plugin includes only registered modules, so a leaf directory nobody registered * is not compiled, not tested and not compared by any gate, while {@code ci} stays green (review * 2026-11-01 08-05). The walk skips the root's own script, every directory with its own settings - * script (a separate build, such as build-logic or optional-platforms), build output, and the + * script (a separate build, such as build-logic), build output, and the * inside of a module's {@code src} tree, where a build script is a test fixture. */ public List unregisteredBuildScripts(File gradleRoot) { 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 a15d3d92..bb5c9d5e 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 @@ -1,6 +1,5 @@ package dev.caskeleton.buildlogic.architecture; -import dev.caskeleton.buildlogic.MainBuild; import dev.caskeleton.buildlogic.ModuleRegistry; import java.io.File; import java.nio.file.Path; @@ -30,13 +29,13 @@ public final class ArchitecturePlugin implements Plugin { @Override public void apply(Project project) { Project root = project.getRootProject(); - boolean optionalGrpcBuild = root.getName().equals("optional-platforms"); - String buildName = optionalGrpcBuild ? "optional-grpc" : "main"; - File mainBuildDirectory = MainBuild.directory(root.getProjectDir()); - File registryFile = new File(mainBuildDirectory, MainBuild.REGISTRY); + // The Gradle root (src/) owns the registry; the repository root is its parent, and every + // source_path in the registry is relative to the repository root. + File mainBuildDirectory = root.getProjectDir(); + File registryFile = new File(mainBuildDirectory, "config/architecture/modules.json"); File repositoryRoot = mainBuildDirectory.getParentFile(); ModuleRegistry registry = ModuleRegistry.read(registryFile, repositoryRoot); - List modules = registry.modulesForBuild(buildName); + List modules = registry.modulesForBuild("main"); List registryViolations = registryViolations(registry, modules); var clean = @@ -50,13 +49,8 @@ public final class ArchitecturePlugin implements Plugin { task.setDescription("Verifies Clean Architecture project dependency direction."); task.getRegistryFile().fileValue(registryFile); task.getRegistryViolations().set(registryViolations); - // The main build owns the whole Gradle root; optional-platforms is a directory - // inside it with its own settings, which the walk skips. task.getUnregisteredBuildScripts() - .set( - optionalGrpcBuild - ? List.of() - : registry.unregisteredBuildScripts(root.getProjectDir())); + .set(registry.unregisteredBuildScripts(root.getProjectDir())); }); var purity = project diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/GrpcPlatformModuleConventionPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/GrpcPlatformModuleConventionPlugin.java deleted file mode 100644 index 145058ca..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/GrpcPlatformModuleConventionPlugin.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.buildlogic.convention; - -import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension; -import org.gradle.api.GradleException; -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.artifacts.VersionCatalogsExtension; - -public final class GrpcPlatformModuleConventionPlugin implements Plugin { - @Override - public void apply(Project project) { - project.getPluginManager().apply("ca.platform-module"); - - var catalogs = project.getExtensions().getByType(VersionCatalogsExtension.class); - var grpc = - catalogs - .named("libs") - .findVersion("grpc") - .orElseThrow( - () -> - new GradleException( - "Version catalog 'libs' must define version 'grpc' for ca.grpc-platform-module")); - String grpcVersion = grpc.getRequiredVersion(); - DependencyManagementExtension dependencyManagement = - project.getExtensions().getByType(DependencyManagementExtension.class); - dependencyManagement.imports(imports -> imports.mavenBom("io.grpc:grpc-bom:" + grpcVersion)); - } -} 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 a33dda25..797a9f02 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 @@ -1,6 +1,5 @@ package dev.caskeleton.buildlogic.java; -import dev.caskeleton.buildlogic.MainBuild; import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension; import java.io.File; import java.io.IOException; @@ -304,13 +303,7 @@ public final class JavaConventionsPlugin implements Plugin { public static final String CONTAINER_IMAGE_PROPERTY_PREFIX = "ca.test.image."; private static File containerImageCatalog(Project project) { - // The optional platform build's root is a directory inside the main build, which owns the - // catalog. - File root = project.getRootProject().getProjectDir(); - File catalog = MainBuild.nearest(root, "config/testing/container-images.properties"); - if (catalog == null) { - catalog = new File(root, "config/testing/container-images.properties"); - } + File catalog = project.getRootProject().file("config/testing/container-images.properties"); if (!catalog.isFile()) { throw new GradleException("Missing test container image catalog: " + catalog); } 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 82b53c5f..c25af918 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 @@ -5,7 +5,6 @@ import com.github.spotbugs.snom.Confidence; import com.github.spotbugs.snom.SpotBugsExtension; import com.github.spotbugs.snom.SpotBugsReport; import com.github.spotbugs.snom.SpotBugsTask; -import dev.caskeleton.buildlogic.MainBuild; import java.io.File; import java.util.List; import net.ltgt.gradle.errorprone.ErrorProneOptions; @@ -37,14 +36,7 @@ public final class QualityConventionsPlugin implements Plugin { SourceSet main = javaExtension.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); SourceSet test = javaExtension.getSourceSets().getByName(SourceSet.TEST_SOURCE_SET_NAME); - // The optional platform build's root is a directory inside the main build, which owns the tool - // configuration. - File repositoryConfigDirectory = - MainBuild.nearest(project.getRootProject().getProjectDir(), "config/checkstyle"); - repositoryConfigDirectory = - repositoryConfigDirectory == null - ? project.getRootProject().file("config") - : repositoryConfigDirectory.getParentFile(); + File repositoryConfigDirectory = project.getRootProject().file("config"); SpotlessExtension spotless = project.getExtensions().getByType(SpotlessExtension.class); spotless.java( @@ -91,7 +83,8 @@ public final class QualityConventionsPlugin implements Plugin { // total 307 46 261 // // Found afterwards and judged the same way (review 15절, r3-L): the optional-platforms (gRPC) - // build reads this same exclude file and had not been analysed at MEDIUM (13), and the + // build, which read this same exclude file until it moved to the grpc-library repository on + // 2026-11-08 (its rows below left with it), had not been analysed at MEDIUM (13), and the // httpclient retry jitter source r3-J added (1). // USO_UNSAFE_METHOD_SYNCHRONIZATION 6 6 - // GrpcAdmissionController: private lock object diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/settings/OptionalArchitectureRegistrySettingsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/settings/OptionalArchitectureRegistrySettingsPlugin.java deleted file mode 100644 index 90b41b7c..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/settings/OptionalArchitectureRegistrySettingsPlugin.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.buildlogic.settings; - -import dev.caskeleton.buildlogic.MainBuild; -import dev.caskeleton.buildlogic.ModuleRegistrySettingsInstaller; -import java.io.File; -import org.gradle.api.Plugin; -import org.gradle.api.initialization.Settings; - -public final class OptionalArchitectureRegistrySettingsPlugin implements Plugin { - @Override - public void apply(Settings settings) { - File mainBuildDirectory = MainBuild.directory(settings.getSettingsDir()); - File registryFile = new File(mainBuildDirectory, MainBuild.REGISTRY); - ModuleRegistrySettingsInstaller.install( - settings, registryFile, mainBuildDirectory.getParentFile(), "optional-grpc"); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java index 03d1dd51..ef53b68e 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java @@ -18,7 +18,8 @@ public abstract class StrictLaneStagesExtension { * command executes this build's stages only when it starts in this build's directory from there * — its step's {@code working-directory} joined with its {@code -p}. The directory is read from * where the build is, so no build states it (review 2026-11-04 RR2-04-04: a {@code -p} value - * alone missed {@code working-directory: src/platforms/optional-build} with {@code ../gradlew}). + * alone missed {@code working-directory: src/platforms/optional-build} with {@code ../gradlew}, in + * the optional gRPC build that has since moved to its own repository). */ public abstract DirectoryProperty getWorkflowDirectory(); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java index 891cdf22..28ca1692 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java @@ -42,9 +42,10 @@ import org.gradle.api.execution.TaskExecutionGraph; * WorkflowGradleInvocations} and {@code ShellScript} name the shapes). * * - *

Each build that holds strict lanes applies it at its own root: the main build, and the - * optional-platforms build. A command executes this build when it starts in this build's directory - * — its step's {@code working-directory}, moved by the {@code cd} commands the same shell surely + *

A build that holds strict lanes applies it at its root (here, the main build; until 2026-11-08 + * the optional gRPC platform build applied it too). A command executes this build when it starts + * in this build's directory — its step's {@code working-directory}, moved by the {@code cd} + * commands the same shell surely * ran before it, joined with its {@code -p}, from the repository root, which is where GitHub keeps * {@code .github/workflows} ({@code ShellScript} says which {@code cd} it follows). * A stage named only by commands that do not count is reported with each command's reason. Applied @@ -298,7 +299,7 @@ public final class StrictLaneStagesPlugin implements Plugin { /** * This build's directory from the repository root, which holds {@code .github/workflows}: {@code - * src} for the main build, {@code src/platforms/optional-build} for the optional one. + * src} for the main build. */ private static String buildDirectory(Project root, File workflowDirectory) { File repository = workflowDirectory.getAbsoluteFile().getParentFile().getParentFile(); 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 a91b3602..861152da 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 @@ -87,7 +87,17 @@ class ModuleRegistryTest { } @Test - void buildOwnershipDefaultsToMainAndCanSelectOptionalModules() throws Exception { + void everyModuleBelongsToTheMainBuild() throws Exception { + ModuleRegistry parsed = read(registry(entry("app-bootstrap", ":app-bootstrap", "src/alpha"))); + assertEquals("main", parsed.byId("app-bootstrap").buildName()); + assertEquals(List.of("app-bootstrap"), parsed.modulesForBuild("main").stream().map(ModuleRegistry.Module::id).toList()); + } + + @Test + void aBuildFieldIsRejectedBecauseNoOtherBuildIncludesOrChecksTheModule() throws Exception { + // The optional gRPC build was the only other build; it moved to its own repository on + // 2026-11-08. A row naming any other build (a typo included) would be included by no settings + // and checked by no direction gate, while ci stays green. Files.createDirectories(root.resolve("src/grpc/grpc-client")); String json = registry( @@ -96,15 +106,13 @@ class ModuleRegistryTest { {"id":"grpc-client","gradle_path":":grpc:grpc-client","source_path":"src/grpc/grpc-client", "allowed_dependencies":[],"build":"optional-grpc"} """); - ModuleRegistry parsed = read(json); - assertEquals("main", parsed.byId("app-bootstrap").buildName()); - assertEquals("optional-grpc", parsed.byId("grpc-client").buildName()); - assertEquals(List.of("app-bootstrap"), parsed.modulesForBuild("main").stream().map(ModuleRegistry.Module::id).toList()); - assertEquals(List.of("grpc-client"), parsed.modulesForBuild("optional-grpc").stream().map(ModuleRegistry.Module::id).toList()); + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json)); + assertTrue(failure.getMessage().contains("'grpc-client'"), failure.getMessage()); + assertTrue(failure.getMessage().contains("'build'"), failure.getMessage()); } @Test - void blankBuildOwnershipIsRefused() { + void aBlankBuildFieldIsRefusedToo() { String json = """ {"modules":[ @@ -112,7 +120,7 @@ class ModuleRegistryTest { "allowed_dependencies":[],"build":" "}]} """; IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json)); - assertTrue(failure.getMessage().contains("nonblank string 'build'"), failure.getMessage()); + assertTrue(failure.getMessage().contains("'build' field"), failure.getMessage()); } @Test diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java index c023c7e4..3fdbd19c 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java @@ -16,7 +16,7 @@ class PlatformModuleConventionTest { @BeforeEach void setUp() throws Exception { Files.createDirectories(projectDir.resolve("gradle")); - writeCatalog(true); + writeCatalog(); // java-conventions refuses a build without the container image catalog (review 2026-11-01 // 08-04); a fixture build that starts no container still has to carry one, even empty. Files.createDirectories(projectDir.resolve("config/testing")); @@ -103,44 +103,6 @@ class PlatformModuleConventionTest { result.getOutput().contains("releaseVersion must be MAJOR.MINOR.PATCH"), result.getOutput()); } - @Test - void grpcConventionImportsBom() throws Exception { - buildFile( - """ - plugins { id 'ca.grpc-platform-module' } - tasks.register('reportManagedVersion') { - String managed = dependencyManagement.managedVersions['io.grpc:grpc-api'] - doLast { logger.lifecycle('managed-grpc-api=' + managed) } - } - """); - BuildResult result = runner("reportManagedVersion").build(); - assertTrue(result.getOutput().contains("managed-grpc-api=1.68.1"), result.getOutput()); - } - - @Test - void grpcConventionRefusesMissingVersion() throws Exception { - writeCatalog(false); - buildFile("plugins { id 'ca.grpc-platform-module' }\n"); - BuildResult result = runner("tasks").buildAndFail(); - assertTrue( - result.getOutput().contains("Version catalog 'libs' must define version 'grpc'"), - result.getOutput()); - } - - @Test - void grpcConventionBringsDependencyManagement() throws Exception { - buildFile( - """ - plugins { id 'ca.grpc-platform-module' } - tasks.register('reportDependencyManagement') { - boolean present = project.extensions.findByName('dependencyManagement') != null - doLast { logger.lifecycle('dependency-management-present=' + present) } - } - """); - BuildResult result = runner("reportDependencyManagement").build(); - assertTrue(result.getOutput().contains("dependency-management-present=true"), result.getOutput()); - } - @Test void pinnedCatalogLibrariesAreManagedAndOthersAreNot() throws Exception { // given: the fixture catalog carries `pinned-fixture` and `unpinned-fixture`. The project-wide @@ -163,7 +125,7 @@ class PlatformModuleConventionTest { assertTrue(result.getOutput().contains("pinned=2.0.1 unpinned=null"), result.getOutput()); } - private void writeCatalog(boolean grpc) throws Exception { + private void writeCatalog() throws Exception { Files.writeString( projectDir.resolve("gradle/libs.versions.toml"), """ @@ -174,12 +136,11 @@ class PlatformModuleConventionTest { spotbugs = "4.10.2" findsecbugs = "1.14.0" errorprone = "2.49.0" - %s [libraries] pinned-fixture = { module = "org.example:pinned-fixture", version = "2.0.1" } unpinned-fixture = { module = "org.example:unpinned-fixture", version = "1.0.0" } - """.formatted(grpc ? "grpc = \"1.68.1\"" : "")); + """); } private void buildFile(String body) throws Exception { diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index 162d6d0f..56691b3d 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -568,90 +568,6 @@ "messaging-policy", "messaging-transport-spi" ] - }, - { - "id": "grpc-contract", - "gradle_path": ":grpc:grpc-contract", - "source_path": "src/platforms/grpc/grpc-contract", - "allowed_dependencies": [], - "build": "optional-grpc" - }, - { - "id": "grpc-core-api", - "gradle_path": ":grpc:grpc-core-api", - "source_path": "src/platforms/grpc/grpc-core-api", - "allowed_dependencies": [], - "build": "optional-grpc" - }, - { - "id": "grpc-observability", - "gradle_path": ":grpc:grpc-observability", - "source_path": "src/platforms/grpc/grpc-observability", - "allowed_dependencies": [ - "grpc-core-api" - ], - "build": "optional-grpc" - }, - { - "id": "grpc-operation-ledger-jpa", - "gradle_path": ":grpc:grpc-operation-ledger-jpa", - "source_path": "src/platforms/grpc/grpc-operation-ledger-jpa", - "allowed_dependencies": [ - "grpc-core-api" - ], - "build": "optional-grpc" - }, - { - "id": "grpc-runtime", - "gradle_path": ":grpc:grpc-runtime", - "source_path": "src/platforms/grpc/grpc-runtime", - "allowed_dependencies": [ - "grpc-core-api" - ], - "build": "optional-grpc" - }, - { - "id": "grpc-spring-boot-starter", - "gradle_path": ":grpc:grpc-spring-boot-starter", - "source_path": "src/platforms/grpc/grpc-spring-boot-starter", - "allowed_dependencies": [ - "grpc-core-api", - "grpc-runtime", - "grpc-observability" - ], - "build": "optional-grpc" - }, - { - "id": "grpc-testkit", - "gradle_path": ":grpc:grpc-testkit", - "source_path": "src/platforms/grpc/grpc-testkit", - "allowed_dependencies": [ - "grpc-core-api", - "grpc-runtime", - "grpc-observability", - "grpc-operation-ledger-jpa" - ], - "build": "optional-grpc" - }, - { - "id": "grpc-advanced", - "gradle_path": ":grpc-advanced:grpc-advanced", - "source_path": "src/platforms/grpc-advanced/grpc-advanced", - "allowed_dependencies": [ - "grpc-core-api", - "grpc-runtime" - ], - "build": "optional-grpc" - }, - { - "id": "grpc-advanced-compat", - "gradle_path": ":grpc-advanced:grpc-advanced-compat", - "source_path": "src/platforms/grpc-advanced/grpc-advanced-compat", - "allowed_dependencies": [ - "grpc-core-api", - "grpc-runtime" - ], - "build": "optional-grpc" } ] } diff --git a/src/config/spotbugs/exclude.xml b/src/config/spotbugs/exclude.xml index 23795b3b..eddd3652 100644 --- a/src/config/spotbugs/exclude.xml +++ b/src/config/spotbugs/exclude.xml @@ -263,14 +263,12 @@ - @@ -284,14 +282,11 @@ is "segment (separator segment)*" where the separator is a character the segment class cannot contain ('.', '-', ';', or a class of those), so each input splits exactly one way and backtracking is linear, not exponential. The application-core and messaging values - also check the length (at most 64-256 characters) before the pattern runs, and so do the - gRPC identifiers (GrpcIdentifiers.requireBounded, 256); JsonPathName and SafeSortField + also check the length (at most 64-256 characters) before the pattern runs; JsonPathName and SafeSortField match developer-declared paths; the SNS host comes from a URI host. --> - - @@ -304,31 +299,13 @@ - - - - - - - - - + owner (PosterImageUploadIntent). A comparison that leaks what the caller already knows leaks nothing. --> @@ -337,21 +314,9 @@ - - - - - - - - diff --git a/src/gradle/libs.versions.toml b/src/gradle/libs.versions.toml index 027477af..fd868f6d 100644 --- a/src/gradle/libs.versions.toml +++ b/src/gradle/libs.versions.toml @@ -54,8 +54,9 @@ googleJavaFormat = "1.35.0" # Pinned (see `pinned-*` below). CVE-2026-102554, fixed in 33.7.2. Brought by gRPC (33.2.1), Error # Prone (33.5.0) and the Checkstyle tool (33.6.0). guava = "33.7.2-jre" -# io.grpc BOM. Read through `ext.grpcVersion`; adapter:inbound:grpc and the five grpc:* leaves -# import it at MODULE scope to keep the strict-locking blast radius off the shared platform. +# io.grpc BOM. adapter:inbound:grpc reads it and imports the BOM at MODULE scope to keep the +# strict-locking blast radius off the shared platform. The gRPC platform library (grpc-library repo, +# Maven group dev.cakit.grpc) pins its own; no catalog entry here until a leaf adopts it. grpc = "1.75.0" jmh = "1.37" jmhPlugin = "0.7.3" @@ -82,10 +83,6 @@ protobuf = "4.33.2" # protobuf-bom import is what resolves, so a lower number here would run gRPC on an older runtime # than it was built against. protobufGrpc = "3.25.8" -# The Gradle plugin that runs protoc for grpc:grpc-contract. protoc and the protobuf-java runtime -# the generated code links against are both `protobufGrpc` above, so generator and runtime move -# together with the gRPC BOM. -protobufPlugin = "0.10.0" # 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" @@ -136,8 +133,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" } -protobuf-java-grpc = { module = "com.google.protobuf:protobuf-java", version.ref = "protobufGrpc" } -protoc = { module = "com.google.protobuf:protoc", version.ref = "protobufGrpc" } 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" } @@ -176,4 +171,3 @@ 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" } -protobuf = { id = "com.google.protobuf", version.ref = "protobufPlugin" } diff --git a/src/platforms/grpc-advanced/AGENTS.md b/src/platforms/grpc-advanced/AGENTS.md deleted file mode 100644 index 6121029a..00000000 --- a/src/platforms/grpc-advanced/AGENTS.md +++ /dev/null @@ -1,88 +0,0 @@ -# grpc-advanced — 고급 gRPC capability의 지역 정본 - -이 문서는 `grpc-advanced:*` family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은 -`src/config/architecture/modules.json`이 SSOT다. 루트 `AGENTS.md`와 충돌하면 -루트가 이긴다. - -이 family는 Stable gRPC 플랫폼(`grpc:*`)이 **의도적으로 제외한** 능력들을 담는다. 별도 디렉터리와 -별도 Gradle prefix인 이유는 하나다: "Stable starter가 advanced module을 참조하면 build가 실패한다"는 -불변 조건을 registry의 `allowed_dependencies`만으로 기계 검증할 수 있게 하기 위해서다. - -## 의존 방향 - -```text -grpc-advanced:* → grpc:* (허용) -grpc:* → grpc-advanced:* (금지 — registry가 거부한다) -``` - -`grpc-spring-boot-starter`의 registry 엔트리에는 어떤 advanced id도 없다. -`verifyCleanArchitectureDependencies`가 build time에 이 규칙을 강제한다. runtime 검사는 없다. - -### 공용 다이제스트 헬퍼를 복사해 두는 이유 - -`grpc-advanced`(`GrpcDiagnosticsRedactor`)는 SHA-256 계산을 자기 안에 둔다. 의존 방향이 -`grpc-advanced:* → grpc:*`로 닫혀 있고 `shared-contract` edge가 없는 것은 의도다. `grpc/AGENTS.md`의 -같은 절과 이유가 같다(vendored 플랫폼, messaging family와 같은 배치). - -## Capability grade와 feature flag - -capability마다 별도 flag를 갖는다. 하나의 "advanced" 스위치로 묶지 않는 이유는, gRPC-Web을 켜는 -결정(프록시 하나)과 xDS를 켜는 결정(control plane과 그 장애 모드 전체)이 같은 결정이 아니기 -때문이다. 하나의 스위치는 두 번째 결정을 실수로 내리게 만든다. - -| grade | 시작 가능 | production 추가 승인 | -| --- | --- | --- | -| `ADVANCED_STABLE` | O | 불필요 | -| `EXPERIMENTAL` | O | **필요** | -| `WATCH` | X (추적만) | — | -| `DISABLED` | X | — | - -property key는 `app.grpc.advanced..enabled`이고 전부 기본 off다. -`GrpcAdvancedModuleGuard`가 세 조건(flag 미설정 / grade가 시작 불가 / production 승인 없음)을 -구분해서 거부하며, 세 경우의 조치가 다르므로 메시지도 다르다. - -## Leaf별 담당 capability - -| leaf | 패키지(`dev.caskeleton.grpc.advanced.*`) | capability | -| --- | --- | --- | -| `grpc-advanced` | `bootstrap` | capability grade, feature flag, module guard, capability별 promotion gate | -| `grpc-advanced` | `edition` | Protobuf Edition 2024 opt-in lane, Edition 2026 watch lane | -| `grpc-advanced` | `streaming` | client streaming(session/dedup/checkpoint), bidi(dual sequence), manual flow control | -| `grpc-advanced` | `resilience`·`discovery`·`xds` | read-only hedging, custom name resolver SPI, custom load balancer SPI, proxyless xDS | -| `grpc-advanced` | `diagnostics` | Channelz/CSDS 진단 | -| `grpc-advanced-compat` | `web`·`integration`·`reactor`·`kotlin` | gRPC-Web, Spring Integration bridge, Reactor adapter, Kotlin coroutine 취소 bridge | - -`grpc-advanced-compat`만 따로 있는 이유는 Reactor·Spring Integration이라는 실제 의존성 경계다. 나머지 -다섯 capability는 framework 의존이 없어 한 leaf에 있다(2026-09-28까지는 leaf 다섯 개). capability별 -독립은 leaf 경계가 아니라 capability flag와 promotion 레코드가 보장한다. 참조 Envoy 설정은 jar에 싣지 -않는 테스트 fixture(`grpc-advanced-compat/src/test/resources/envoy/envoy.yaml`)다. - -## Promotion은 capability별로 독립이다 - -승격 증거는 capability마다 따로 판단한다. 공유 증거였다면 하나를 승격할 때 같은 시점에 측정된 다른 -것들이 함께 승격된다. 이 규칙을 코드로 옮겨 두었던 `GrpcAdvancedPromotionGate`는 자기 테스트 말고 -호출처가 없어 2026-09-25 리뷰 후속 작업에서 삭제했다. 지금은 `docs/runbooks/grpc-advanced-capabilities.md`의 -리뷰 규칙이다. - -승격 문턱은 두 개다: `ADVANCED_STABLE`은 7일 soak + 전체 증거, Stable default는 30일 soak. 두 번째가 -더 높은 이유는 모든 배포가 그 의존성과 장애 모드를 갖게 되기 때문이다. - -## 이 저장소에서 검증할 수 없는 것 - -capability별로 필요한 실제 인프라가 이 저장소에 없다. - -- `grpc-web` → gRPC-Web 프록시 -- `servlet-compat` → Servlet 컨테이너 -- `xds` → 중지 가능한 xDS control plane -- `kotlin` → Kotlin 툴체인 - -인프라 없이 도는 suite는 통과하면서 아무것도 증명하지 않으므로, suite가 없는 것보다 나쁘다. -이 사실을 상수로 반환하던 gate 클래스(`GrpcKotlinCompatibilityGate`, `GrpcAdvancedInfrastructureTestkit` -등)는 2026-09-25 삭제됐다 — 지원 여부는 이 문서와 support matrix가 적는다. - -## 금지 - -- Stable leaf(`grpc:*`)가 이 family를 참조하는 것. -- capability grade 없이, 또는 flag 없이 advanced 코드 경로를 실행하는 것. -- `WATCH` capability를 스키마 소스로 사용하는 것. -- 실제 인프라 없이 실행한 suite를 promotion evidence로 인용하는 것. diff --git a/src/platforms/grpc-advanced/CLAUDE.md b/src/platforms/grpc-advanced/CLAUDE.md deleted file mode 100644 index 43c994c2..00000000 --- a/src/platforms/grpc-advanced/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -@AGENTS.md diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/build.gradle b/src/platforms/grpc-advanced/grpc-advanced-compat/build.gradle deleted file mode 100644 index bf0fccdb..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/build.gradle +++ /dev/null @@ -1,24 +0,0 @@ -plugins { - // grpc-platform, not platform: grpc-runtime's io.grpc api dependencies are versionless and - // need the gRPC BOM on every classpath they reach. - id 'ca.grpc-platform-module' -} - -// Compatibility bridges: gRPC-Web, the Spring Integration bridge, the Reactor adapter, and the -// Kotlin coroutine cancellation bridge. -// -// No Kotlin source set (adaptation D7): this repository has no Kotlin toolchain, so the Kotlin side -// is only the Java-side cancellation bridge; nothing here claims Kotlin support. -// -// The reference Envoy configuration is a test fixture (src/test/resources/envoy), not something -// this jar ships: a proxy configuration belongs to the deployment that runs the proxy. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-runtime') - - // api: the Reactor adapter's public signatures are Mono/Flux, and the Integration gateways name - // Spring Integration's Message. Hiding either would only stop an adopter compiling against the - // API this module documents. - api 'io.projectreactor:reactor-core' - api 'org.springframework.integration:spring-integration-core' -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/gradle.lockfile b/src/platforms/grpc-advanced/grpc-advanced-compat/gradle.lockfile deleted file mode 100644 index a6365b94..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/gradle.lockfile +++ /dev/null @@ -1,98 +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,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -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.50.0=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -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,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -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 -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.grpc:grpc-api:1.75.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.grpc:grpc-stub:1.75.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-commons:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.8=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.mojo:animal-sniffer-annotations:1.24=compileClasspath,runtimeClasspath,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.6.1=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,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 -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.20=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.20=checkstyle -org.springframework.integration:spring-integration-core:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-messaging:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationBridgePolicy.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationBridgePolicy.java deleted file mode 100644 index 0ae324aa..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationBridgePolicy.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.grpc.advanced.integration; - -import dev.caskeleton.grpc.api.context.GrpcMetadataKey; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** - * What a Spring Integration flow may exchange with a gRPC call. - * - *

The header allowlist is the whole policy. A Spring Integration {@code Message} accumulates - * headers as it moves through a flow — routing keys, correlation ids, errors channels, whatever a - * transformer added — and copying them onto gRPC metadata sends a service's internal plumbing - * across the network, where it counts against the metadata budget and occasionally carries - * something sensitive. - * - *

The bridge does not add durability. Spring Integration channels can look like a broker, and a - * bridge that implied acknowledgement or redelivery semantics would be promising something gRPC - * does not do. - */ -public record GrpcIntegrationBridgePolicy( - Set headerAllowlist, Set payloadConverters) { - - /** Copies both sets and refuses a bridge with no converter. */ - public GrpcIntegrationBridgePolicy { - if (headerAllowlist == null || payloadConverters == null) { - throw new IllegalArgumentException("a bridge policy states its allowlist and converters"); - } - headerAllowlist = Set.copyOf(headerAllowlist); - payloadConverters = Set.copyOf(payloadConverters); - if (payloadConverters.isEmpty()) { - throw new IllegalArgumentException( - "a bridge with no registered converter cannot turn a Message payload into a request; " - + "leaving it to reflection is how an unexpected type reaches the wire"); - } - } - - /** The metadata that survives from a Message's headers. */ - public Map metadataFrom(Map messageHeaders) { - if (messageHeaders == null) { - throw new IllegalArgumentException("message headers must not be null"); - } - Map metadata = new LinkedHashMap<>(); - headerAllowlist.forEach( - key -> { - Object value = messageHeaders.get(key.name()); - if (value != null) { - metadata.put(key, String.valueOf(value)); - } - }); - return Map.copyOf(metadata); - } - - /** Whether a payload type has a registered converter. */ - public boolean converterRegistered(String payloadType) { - return payloadConverters.contains(payloadType); - } - - /** - * Whether the bridge provides broker-style acknowledgement or redelivery. - * - *

Always false. A bridge that implied either would be promising a delivery guarantee gRPC does - * not make. - */ - public boolean providesBrokerSemantics() { - return false; - } - - /** - * Whether the bridge replaces the generated stub and service APIs. - * - *

Always false. It is one way to reach a gRPC call from an existing integration flow, not the - * way an application is meant to call one. - */ - public boolean replacesGeneratedApis() { - return false; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationInboundGateway.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationInboundGateway.java deleted file mode 100644 index 92dfb5a3..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationInboundGateway.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.grpc.advanced.integration; - -import dev.caskeleton.grpc.api.context.GrpcRequestContext; -import java.util.Map; -import org.springframework.messaging.Message; -import org.springframework.messaging.support.MessageBuilder; - -/** - * Turns an inbound gRPC call into a Spring Integration {@code Message}. - * - *

The request context travels as one header holding the immutable context object, rather than as - * a scattering of actor, tenant and deadline headers. Flattening it would let a transformer in the - * middle of a flow change the tenant of a request that has already been authenticated. - * - * @param the request payload type - */ -public final class GrpcIntegrationInboundGateway { - - /** The header the immutable request context travels under. */ - public static final String CONTEXT_HEADER = "grpcRequestContext"; - - private final GrpcIntegrationBridgePolicy policy; - - /** Binds a gateway to its bridge policy. */ - public GrpcIntegrationInboundGateway(GrpcIntegrationBridgePolicy policy) { - if (policy == null) { - throw new IllegalArgumentException("an inbound gateway needs a bridge policy"); - } - this.policy = policy; - } - - /** - * Builds the Message a flow receives. - * - * @throws IllegalArgumentException when the payload type has no registered converter - */ - public Message toMessage(Q payload, GrpcRequestContext context) { - if (payload == null || context == null) { - throw new IllegalArgumentException("an inbound message needs a payload and a context"); - } - String payloadType = payload.getClass().getName(); - if (!policy.converterRegistered(payloadType)) { - throw new IllegalArgumentException( - "no converter is registered for '" - + payloadType - + "'; converting by reflection is how an unexpected type reaches a flow"); - } - Map headers = new java.util.LinkedHashMap<>(); - headers.put(CONTEXT_HEADER, context); - context.metadata().forEach((key, value) -> headers.put(key.name(), value)); - return MessageBuilder.withPayload(payload).copyHeaders(headers).build(); - } - - /** The policy in force. */ - public GrpcIntegrationBridgePolicy policy() { - return policy; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationOutboundGateway.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationOutboundGateway.java deleted file mode 100644 index 08163fd0..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/integration/GrpcIntegrationOutboundGateway.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.grpc.advanced.integration; - -import dev.caskeleton.grpc.api.context.GrpcMetadataKey; -import java.util.Map; -import org.springframework.messaging.Message; - -/** - * Turns an outbound Spring Integration {@code Message} into a gRPC call's inputs. - * - *

Applies the header allowlist rather than copying what the flow accumulated. A flow's headers - * are its own bookkeeping; putting them on the wire spends the metadata budget on another service's - * plumbing and occasionally sends something that should not leave the process. - * - * @param the request payload type - */ -public final class GrpcIntegrationOutboundGateway { - - private final GrpcIntegrationBridgePolicy policy; - - /** Binds a gateway to its bridge policy. */ - public GrpcIntegrationOutboundGateway(GrpcIntegrationBridgePolicy policy) { - if (policy == null) { - throw new IllegalArgumentException("an outbound gateway needs a bridge policy"); - } - this.policy = policy; - } - - /** The metadata this message contributes to the call. */ - public Map metadataFrom(Message message) { - if (message == null) { - throw new IllegalArgumentException("an outbound message is required"); - } - return policy.metadataFrom(message.getHeaders()); - } - - /** - * The payload to send. - * - * @throws IllegalArgumentException when the payload type has no registered converter - */ - public C payloadFrom(Message message) { - if (message == null) { - throw new IllegalArgumentException("an outbound message is required"); - } - C payload = message.getPayload(); - String payloadType = payload.getClass().getName(); - if (!policy.converterRegistered(payloadType)) { - throw new IllegalArgumentException("no converter is registered for '" + payloadType + "'"); - } - return payload; - } - - /** The policy in force. */ - public GrpcIntegrationBridgePolicy policy() { - return policy; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcCoroutineContextBridge.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcCoroutineContextBridge.java deleted file mode 100644 index 47086224..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcCoroutineContextBridge.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.grpc.advanced.kotlin; - -import dev.caskeleton.grpc.deadline.GrpcCancellationCoordinator; -import dev.caskeleton.grpc.deadline.GrpcCancellationReason; -import java.time.Instant; -import java.util.function.Supplier; - -/** - * The contract a Kotlin coroutine adapter has to satisfy, expressed as Java callbacks. - * - *

Callbacks rather than coroutine types, so the rule is checkable without a Kotlin toolchain. A - * Kotlin adapter wires its {@code Job} completion handler to {@link #onCoroutineCancelled} and its - * cancellation source to {@link #cancelCoroutineScope}; what the platform needs is that both - * directions exist, and that is what this makes assertable. - */ -public final class GrpcCoroutineContextBridge { - - private GrpcCoroutineContextBridge() {} - - /** - * What a Kotlin adapter calls when its coroutine scope is cancelled. - * - *

Coroutine cancellation is cooperative and structured: cancelling a scope cancels its - * children, and a gRPC call started inside it is not one of them unless something says so. - */ - public static Runnable onCoroutineCancelled( - GrpcCancellationCoordinator coordinator, Supplier now) { - if (coordinator == null || now == null) { - throw new IllegalArgumentException("the bridge needs a coordinator and a clock"); - } - return () -> coordinator.cancel(GrpcCancellationReason.CLIENT_CANCELLED, now.get()); - } - - /** - * Registers the coroutine scope so a platform cancellation reaches it. - * - * @param cancelScope what the Kotlin side does to cancel its scope - */ - public static void cancelCoroutineScope( - GrpcCancellationCoordinator coordinator, Runnable cancelScope, String operationName) { - if (coordinator == null || cancelScope == null) { - throw new IllegalArgumentException("the bridge needs a coordinator and a cancel action"); - } - if (operationName == null || operationName.isBlank()) { - throw new IllegalArgumentException("a cancellable operation needs a name"); - } - coordinator.register( - new dev.caskeleton.grpc.deadline.GrpcCancellableOperation() { - @Override - public String name() { - return operationName; - } - - @Override - public void cancel(GrpcCancellationReason reason) { - cancelScope.run(); - } - }); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/GrpcReactorCancellationBridge.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/GrpcReactorCancellationBridge.java deleted file mode 100644 index 52ce308c..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/GrpcReactorCancellationBridge.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.grpc.advanced.reactor; - -import dev.caskeleton.grpc.deadline.GrpcCancellationCoordinator; -import dev.caskeleton.grpc.deadline.GrpcCancellationReason; -import java.time.Instant; -import java.util.function.Supplier; -import reactor.core.Disposable; - -/** - * Turns a Reactor subscription's cancellation into the platform's. - * - *

Both directions, and both are needed. A client that disposes its {@code Mono} has stopped - * caring, and without this bridge the server keeps computing an answer nobody will read; a call the - * platform cancelled — deadline, drain, revoked credential — has to stop the reactive pipeline, or - * the work continues after the response has been closed. - */ -public final class GrpcReactorCancellationBridge { - - private GrpcReactorCancellationBridge() {} - - /** - * A callback for {@code doOnCancel} that cancels the platform call. - * - * @param now supplies the moment, so a test does not depend on the wall clock - */ - public static Runnable onReactorCancel( - GrpcCancellationCoordinator coordinator, Supplier now) { - if (coordinator == null || now == null) { - throw new IllegalArgumentException("a cancellation bridge needs a coordinator and a clock"); - } - return () -> coordinator.cancel(GrpcCancellationReason.CLIENT_CANCELLED, now.get()); - } - - /** - * Disposes the reactive pipeline when the platform cancels. - * - *

Registered as a cancellable operation, so it is reached by the same cancellation that stops - * the database query and the stream writer rather than by a second mechanism. - */ - public static void bindPlatformCancellation( - GrpcCancellationCoordinator coordinator, Disposable subscription, String operationName) { - if (coordinator == null || subscription == null) { - throw new IllegalArgumentException("binding needs a coordinator and a subscription"); - } - if (operationName == null || operationName.isBlank()) { - throw new IllegalArgumentException("a cancellable operation needs a name"); - } - coordinator.register( - new dev.caskeleton.grpc.deadline.GrpcCancellableOperation() { - @Override - public String name() { - return operationName; - } - - @Override - public void cancel(GrpcCancellationReason reason) { - subscription.dispose(); - } - }); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/GrpcReactorContextBridge.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/GrpcReactorContextBridge.java deleted file mode 100644 index 8eccbdcf..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/GrpcReactorContextBridge.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.grpc.advanced.reactor; - -import dev.caskeleton.grpc.context.GrpcContextSnapshot; -import java.util.Optional; -import reactor.util.context.Context; -import reactor.util.context.ContextView; - -/** - * Carries the call context between gRPC's {@code Context} and Reactor's. - * - *

Explicitly, because neither propagates into the other. gRPC's context is a thread-local - * mechanism and Reactor's travels with the subscription, so an operator that hops threads leaves - * the gRPC context behind and a gRPC interceptor cannot see the Reactor one. Work downstream of - * that boundary then runs with no actor, no tenant and no deadline, which is the failure that - * produces a change attributed to nobody. - */ -public final class GrpcReactorContextBridge { - - private static final String CONTEXT_KEY = "dev.caskeleton.grpc.contextSnapshot"; - - private GrpcReactorContextBridge() {} - - /** Puts the snapshot into a Reactor context. */ - public static Context write(Context context, GrpcContextSnapshot snapshot) { - if (context == null || snapshot == null) { - throw new IllegalArgumentException("bridging needs a Reactor context and a snapshot"); - } - return context.put(CONTEXT_KEY, snapshot); - } - - /** Reads the snapshot out of a Reactor context, if it is there. */ - public static Optional read(ContextView context) { - if (context == null) { - throw new IllegalArgumentException("a Reactor context view is required"); - } - return context.hasKey(CONTEXT_KEY) ? Optional.of(context.get(CONTEXT_KEY)) : Optional.empty(); - } - - /** - * Reads the snapshot, failing when it is absent. - * - * @throws IllegalStateException because reactive work with no call context has no actor, no - * tenant and no deadline - */ - public static GrpcContextSnapshot require(ContextView context) { - return read(context) - .orElseThrow( - () -> - new IllegalStateException( - "no gRPC call context is in the Reactor context; reactive work that runs " - + "without one produces a change attributed to nobody")); - } - - /** The key the snapshot travels under, for a test or a diagnostic to look at. */ - public static String contextKey() { - return CONTEXT_KEY; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/ReactiveGrpcClient.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/ReactiveGrpcClient.java deleted file mode 100644 index fc0988d0..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/ReactiveGrpcClient.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.grpc.advanced.reactor; - -import dev.caskeleton.grpc.context.GrpcContextSnapshot; -import java.util.List; -import java.util.function.Supplier; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Exposes a unary call as a {@code Mono} and a server stream as a {@code Flux}. - * - *

Only here. The Stable contract types stay free of Reactor, so a deployment that does not use - * it does not carry it, and the reactive shape is a view over the platform rather than the - * platform's own vocabulary. - * - *

The {@code Flux} respects the Stable bounded flow control rather than replacing it. Reactor's - * backpressure and gRPC's are two mechanisms over one connection; letting a subscriber's {@code - * request(n)} drive the writer directly would bypass the bounded queue that decides what happens - * when a consumer falls behind. - */ -public final class ReactiveGrpcClient { - - private ReactiveGrpcClient() {} - - /** - * A unary call as a {@code Mono}, with the call context carried in the Reactor context. - * - * @param call the blocking invocation, run on {@code boundedElasticScheduler} rather than on the - * calling thread. A blocking call on an event loop stalls every other call sharing it, and - * the mistake is invisible until load arrives. - */ - public static Mono unary( - Supplier call, GrpcContextSnapshot snapshot, reactor.core.scheduler.Scheduler blocking) { - if (call == null || snapshot == null || blocking == null) { - throw new IllegalArgumentException( - "a reactive unary call needs an invocation, a context and a scheduler"); - } - return Mono.fromSupplier(call) - .subscribeOn(blocking) - .contextWrite(context -> GrpcReactorContextBridge.write(context, snapshot)); - } - - /** - * A server stream as a {@code Flux}. - * - * @param messages the already-bounded message source. Taking a list rather than a producer is - * deliberate: the bound belongs to the Stable stream writer, and a producer here would be a - * second place to get it wrong. - */ - public static Flux serverStream(List messages, GrpcContextSnapshot snapshot) { - if (messages == null || snapshot == null) { - throw new IllegalArgumentException("a reactive stream needs its messages and a context"); - } - return Flux.fromIterable(messages) - .contextWrite(context -> GrpcReactorContextBridge.write(context, snapshot)); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/ReactiveGrpcServerAdapter.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/ReactiveGrpcServerAdapter.java deleted file mode 100644 index 3c656bc4..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/reactor/ReactiveGrpcServerAdapter.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.grpc.advanced.reactor; - -import dev.caskeleton.grpc.api.context.GrpcRequestContext; -import dev.caskeleton.grpc.context.GrpcContextSnapshot; -import java.util.function.BiFunction; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; - -/** - * Runs a reactive use case behind a gRPC service adapter. - * - *

The blocking scheduler is a required argument rather than a default. A reactive pipeline that - * touches JPA or a blocking SDK and does not say where that happens runs it on the event loop, and - * the symptom — every call on the connection slowing together — appears only under load and points - * at the wrong component. - * - * @param the application command type - * @param the application result type - */ -public final class ReactiveGrpcServerAdapter { - - private final BiFunction> useCase; - private final Scheduler blockingScheduler; - - /** Binds an adapter to its use case and the scheduler blocking work runs on. */ - public ReactiveGrpcServerAdapter( - BiFunction> useCase, Scheduler blockingScheduler) { - if (useCase == null || blockingScheduler == null) { - throw new IllegalArgumentException( - "a reactive adapter needs a use case and the scheduler its blocking work runs on"); - } - this.useCase = useCase; - this.blockingScheduler = blockingScheduler; - } - - /** - * Invokes the use case with the context in both the Reactor context and the argument. - * - *

Both, because they are read by different code: application operators read the Reactor - * context, and the use case signature reads the argument. Supplying only one leaves the other - * empty at a boundary nobody expects. - */ - public Mono invoke(C command, GrpcRequestContext context, GrpcContextSnapshot snapshot) { - if (command == null || context == null || snapshot == null) { - throw new IllegalArgumentException( - "an invocation needs a command, a request context and the snapshot to carry"); - } - return Mono.defer(() -> useCase.apply(command, context)) - .subscribeOn(blockingScheduler) - .contextWrite(reactorContext -> GrpcReactorContextBridge.write(reactorContext, snapshot)); - } - - /** The scheduler blocking work runs on. */ - public Scheduler blockingScheduler() { - return blockingScheduler; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebProfile.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebProfile.java deleted file mode 100644 index 194bd33a..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebProfile.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.grpc.advanced.web; - -import java.util.Set; - -/** - * How a browser reaches the platform, and under what browser-specific rules. - * - *

Cookie credentials and bearer credentials are separated because their attack surfaces differ. - * A cookie is attached by the browser to every request to the origin, which makes CSRF a real - * concern and a CSRF defence mandatory; a bearer token the application attaches explicitly is not - * sent automatically, and requiring a CSRF token there is ceremony. A profile that treats them the - * same either leaves the first exposed or burdens the second. - */ -public record GrpcWebProfile( - CredentialStyle credentialStyle, - Set allowedOrigins, - boolean csrfProtection, - boolean tlsTerminatedAtProxy) { - - /** How the browser presents its credential. */ - public enum CredentialStyle { - /** No credential. */ - NONE, - /** A cookie the browser attaches automatically. Needs a CSRF defence. */ - COOKIE, - /** A bearer token the application attaches explicitly. */ - BEARER - } - - /** Refuses a profile a browser could be tricked into using. */ - public GrpcWebProfile { - if (credentialStyle == null) { - throw new IllegalArgumentException("a gRPC-Web profile names its credential style"); - } - if (allowedOrigins == null) { - throw new IllegalArgumentException("a gRPC-Web profile states its origin allowlist"); - } - allowedOrigins = Set.copyOf(allowedOrigins); - if (allowedOrigins.contains("*")) { - throw new IllegalArgumentException( - "a wildcard origin lets any site call this API with the browser's ambient credentials"); - } - if (credentialStyle != CredentialStyle.NONE && allowedOrigins.isEmpty()) { - throw new IllegalArgumentException( - "a credentialed gRPC-Web profile needs an origin allowlist"); - } - if (credentialStyle == CredentialStyle.COOKIE && !csrfProtection) { - throw new IllegalArgumentException( - "cookie credentials are attached by the browser to every request to this origin, so a " - + "CSRF defence is not optional"); - } - if (!tlsTerminatedAtProxy && credentialStyle != CredentialStyle.NONE) { - throw new IllegalArgumentException( - "a credentialed browser call needs TLS terminated at the proxy"); - } - } - - /** A bearer-token profile for a single origin. */ - public static GrpcWebProfile bearer(String origin) { - return new GrpcWebProfile(CredentialStyle.BEARER, Set.of(origin), false, true); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebProxyContract.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebProxyContract.java deleted file mode 100644 index ba27ad13..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebProxyContract.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.grpc.advanced.web; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * What a gRPC-Web proxy must be configured to do. - * - *

The exposed-trailer rule is the one that costs the most time when it is missing. A gRPC status - * arrives as a trailer, a browser cannot read a trailer the proxy did not expose, and the symptom - * is a call that appears to succeed at the network level and produces no status at all — which - * looks like an application bug and is a proxy configuration. - */ -public final class GrpcWebProxyContract { - - /** The trailers a browser client has to be able to read. */ - private static final Set REQUIRED_EXPOSED_HEADERS = Set.of("grpc-status", "grpc-message"); - - private GrpcWebProxyContract() {} - - /** The headers a proxy must expose. */ - public static Set requiredExposedHeaders() { - return REQUIRED_EXPOSED_HEADERS; - } - - /** - * Every problem with a proxy configuration. - * - * @param exposedHeaders the CORS {@code expose_headers} the proxy is configured with - * @param allowedOrigins the CORS origin allowlist the proxy is configured with - * @return an empty list when the proxy would work for a browser client - */ - public static List violations( - GrpcWebProfile profile, Set exposedHeaders, Set allowedOrigins) { - if (profile == null || exposedHeaders == null || allowedOrigins == null) { - throw new IllegalArgumentException("a proxy check needs the profile and both CORS sets"); - } - List violations = new ArrayList<>(); - - REQUIRED_EXPOSED_HEADERS.stream() - .sorted() - .filter(header -> !exposedHeaders.contains(header)) - .forEach( - header -> - violations.add( - "the proxy does not expose '" - + header - + "'; a browser cannot read a trailer it was not given, so the call " - + "produces no status at all")); - - if (allowedOrigins.contains("*")) { - violations.add("the proxy allows any origin, which defeats the profile's allowlist"); - } - profile.allowedOrigins().stream() - .sorted() - .filter(origin -> !allowedOrigins.contains(origin)) - .forEach( - origin -> - violations.add( - "origin '" + origin + "' is in the profile but not in the proxy's allowlist")); - return List.copyOf(violations); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebRpcSupport.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebRpcSupport.java deleted file mode 100644 index 4005352e..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebRpcSupport.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.grpc.advanced.web; - -import dev.caskeleton.grpc.core.RpcType; - -/** - * Which RPC shapes gRPC-Web can actually carry. - * - *

Two, and the limit is the protocol's rather than this platform's: gRPC-Web has no way for a - * browser to send a stream of messages, so client and bidirectional streaming are not slow or - * partial there — they do not exist. Declaring support for them produces a schema a browser client - * cannot use and a discovery that happens in the browser. - */ -public final class GrpcWebRpcSupport { - - private GrpcWebRpcSupport() {} - - /** Whether {@code rpcType} can travel over gRPC-Web. */ - public static boolean supported(RpcType rpcType) { - if (rpcType == null) { - throw new IllegalArgumentException("an RPC type is required"); - } - return rpcType == RpcType.UNARY || rpcType == RpcType.SERVER_STREAMING; - } - - /** - * Fails when a method shape cannot be served over gRPC-Web. - * - * @throws IllegalArgumentException naming what the browser cannot do - */ - public static void require(RpcType rpcType) { - if (!supported(rpcType)) { - throw new IllegalArgumentException( - rpcType - + " cannot travel over gRPC-Web: a browser has no way to send a stream of messages, " - + "so declaring support for it produces a schema no browser client can use"); - } - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcCoroutineContextBridgeTest.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcCoroutineContextBridgeTest.java deleted file mode 100644 index cb5b08da..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcCoroutineContextBridgeTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.grpc.advanced.compat; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.kotlin.GrpcCoroutineContextBridge; -import dev.caskeleton.grpc.api.deadline.GrpcCancellationToken; -import dev.caskeleton.grpc.deadline.GrpcCancellationCoordinator; -import dev.caskeleton.grpc.deadline.GrpcCancellationReason; -import java.time.Instant; -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcCoroutineContextBridgeTest { - - private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - - @Test - @DisplayName("coroutine cancellation reaches the platform, and the platform reaches the scope") - void cancellationCrossesBothWays() { - GrpcCancellationCoordinator inbound = - new GrpcCancellationCoordinator(new GrpcCancellationToken()); - GrpcCoroutineContextBridge.onCoroutineCancelled(inbound, () -> NOW).run(); - assertThat(inbound.cancelled()).isTrue(); - - GrpcCancellationCoordinator outbound = - new GrpcCancellationCoordinator(new GrpcCancellationToken()); - AtomicBoolean scopeCancelled = new AtomicBoolean(); - GrpcCoroutineContextBridge.cancelCoroutineScope( - outbound, () -> scopeCancelled.set(true), "document-flow"); - outbound.cancel(GrpcCancellationReason.SERVER_DRAIN, NOW); - - assertThat(scopeCancelled).isTrue(); - } - - @Test - @DisplayName("binding a coroutine scope without a name is refused") - void bindingNeedsAnOperationName() { - GrpcCancellationCoordinator coordinator = - new GrpcCancellationCoordinator(new GrpcCancellationToken()); - - assertThatThrownBy( - () -> GrpcCoroutineContextBridge.cancelCoroutineScope(coordinator, () -> {}, " ")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcIntegrationBridgePolicyTest.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcIntegrationBridgePolicyTest.java deleted file mode 100644 index b687080e..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcIntegrationBridgePolicyTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.grpc.advanced.compat; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.integration.GrpcIntegrationBridgePolicy; -import dev.caskeleton.grpc.advanced.integration.GrpcIntegrationInboundGateway; -import dev.caskeleton.grpc.advanced.integration.GrpcIntegrationOutboundGateway; -import dev.caskeleton.grpc.api.context.GrpcClientIdentity; -import dev.caskeleton.grpc.api.context.GrpcMetadataBudget; -import dev.caskeleton.grpc.api.context.GrpcMetadataKey; -import dev.caskeleton.grpc.api.context.GrpcRequestContext; -import dev.caskeleton.grpc.api.deadline.GrpcCancellationToken; -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineBudget; -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import java.time.Duration; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.messaging.Message; -import org.springframework.messaging.support.MessageBuilder; - -class GrpcIntegrationBridgePolicyTest { - - private static final GrpcMetadataKey CORRELATION = GrpcMetadataKey.ascii("x-correlation-id"); - private static final GrpcMethodName GET = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - - private static GrpcRequestContext requestContext() { - return GrpcRequestContext.create( - GET, - RpcType.UNARY, - GrpcClientIdentity.fromVerifiedAuthentication("actor-1", "tenant-1", "jwt-issuer"), - GrpcDeadlineBudget.forEntryPoint( - Duration.ofSeconds(1), GrpcDeadlineProfile.of(Duration.ofSeconds(2))), - new GrpcCancellationToken(), - Map.of(CORRELATION, "corr-1"), - Set.of(CORRELATION), - GrpcMetadataBudget.standard(), - null); - } - - private static GrpcIntegrationBridgePolicy policy() { - return new GrpcIntegrationBridgePolicy(Set.of(CORRELATION), Set.of(String.class.getName())); - } - - @Test - @DisplayName("the bridge copies only allowlisted headers onto metadata") - void theBridgeCopiesOnlyAllowlistedHeaders() { - GrpcIntegrationOutboundGateway outbound = - new GrpcIntegrationOutboundGateway<>(policy()); - Message message = - MessageBuilder.withPayload("payload") - .setHeader(CORRELATION.name(), "corr-1") - .setHeader("errorChannel", "internal-errors") - .setHeader("replyChannel", "internal-replies") - .build(); - - assertThat(outbound.metadataFrom(message)).containsOnlyKeys(CORRELATION); - assertThat(outbound.payloadFrom(message)).isEqualTo("payload"); - assertThat(outbound.policy()).isNotNull(); - } - - @Test - @DisplayName("an unregistered payload type is refused rather than converted by reflection") - void anUnregisteredPayloadIsRefused() { - GrpcIntegrationBridgePolicy otherType = - new GrpcIntegrationBridgePolicy(Set.of(CORRELATION), Set.of("some.other.Type")); - GrpcIntegrationInboundGateway inbound = new GrpcIntegrationInboundGateway<>(otherType); - - assertThatThrownBy(() -> inbound.toMessage("payload", requestContext())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("converting by reflection"); - Message message = MessageBuilder.withPayload("payload").build(); - GrpcIntegrationOutboundGateway outbound = - new GrpcIntegrationOutboundGateway<>(otherType); - assertThatThrownBy(() -> outbound.payloadFrom(message)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a bridge with no registered converter is refused at construction") - void aBridgeWithNoConverterIsRefused() { - assertThatThrownBy(() -> new GrpcIntegrationBridgePolicy(Set.of(), Set.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("leaving it to reflection"); - } - - @Test - @DisplayName("the request context travels as one immutable header, not as scattered fields") - void theContextTravelsAsOneHeader() { - GrpcIntegrationInboundGateway inbound = new GrpcIntegrationInboundGateway<>(policy()); - - Message message = inbound.toMessage("payload", requestContext()); - - assertThat(message.getHeaders()) - .containsKey(GrpcIntegrationInboundGateway.CONTEXT_HEADER) - .containsKey(CORRELATION.name()) - .doesNotContainKey("tenantId") - .doesNotContainKey("actorId"); - } - - @Test - @DisplayName("the bridge adds no broker semantics and replaces no generated API") - void theBridgeClaimsNothingItCannotDo() { - assertThat(policy().providesBrokerSemantics()).isFalse(); - assertThat(policy().replacesGeneratedApis()).isFalse(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcReactorContextBridgeTest.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcReactorContextBridgeTest.java deleted file mode 100644 index ee4d99b6..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcReactorContextBridgeTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.grpc.advanced.compat; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.reactor.GrpcReactorCancellationBridge; -import dev.caskeleton.grpc.advanced.reactor.GrpcReactorContextBridge; -import dev.caskeleton.grpc.api.context.GrpcClientIdentity; -import dev.caskeleton.grpc.api.context.GrpcMetadataBudget; -import dev.caskeleton.grpc.api.context.GrpcRequestContext; -import dev.caskeleton.grpc.api.deadline.GrpcCancellationToken; -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineBudget; -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; -import dev.caskeleton.grpc.context.GrpcContextSnapshot; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import dev.caskeleton.grpc.deadline.GrpcCancellationCoordinator; -import dev.caskeleton.grpc.deadline.GrpcCancellationReason; -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import reactor.util.context.Context; - -class GrpcReactorContextBridgeTest { - - private static final GrpcMethodName GET = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - - private static GrpcContextSnapshot snapshot() { - GrpcRequestContext request = - GrpcRequestContext.create( - GET, - RpcType.UNARY, - GrpcClientIdentity.fromVerifiedAuthentication("actor-1", "tenant-1", "jwt-issuer"), - GrpcDeadlineBudget.forEntryPoint( - Duration.ofSeconds(1), GrpcDeadlineProfile.of(Duration.ofSeconds(2))), - new GrpcCancellationToken(), - Map.of(), - Set.of(), - GrpcMetadataBudget.standard(), - null); - return GrpcContextSnapshot.of(request, null); - } - - @Test - @DisplayName("the call context crosses into and out of a Reactor context") - void theContextCrossesIntoReactor() { - GrpcContextSnapshot snapshot = snapshot(); - - Context context = GrpcReactorContextBridge.write(Context.empty(), snapshot); - - assertThat(GrpcReactorContextBridge.read(context)).contains(snapshot); - assertThat(GrpcReactorContextBridge.require(context).identity().actorId()).isEqualTo("actor-1"); - assertThat(GrpcReactorContextBridge.contextKey()).isNotBlank(); - } - - @Test - @DisplayName("reactive work with no call context fails closed") - void contextlessReactiveWorkFailsClosed() { - assertThat(GrpcReactorContextBridge.read(Context.empty())).isEmpty(); - assertThatThrownBy(() -> GrpcReactorContextBridge.require(Context.empty())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("attributed to nobody"); - } - - @Test - @DisplayName("a Reactor cancellation reaches the platform coordinator") - void reactorCancellationReachesThePlatform() { - GrpcCancellationCoordinator coordinator = - new GrpcCancellationCoordinator(new GrpcCancellationToken()); - - GrpcReactorCancellationBridge.onReactorCancel(coordinator, () -> NOW).run(); - - assertThat(coordinator.cancelled()).isTrue(); - assertThat(coordinator.reason()).contains(GrpcCancellationReason.CLIENT_CANCELLED); - } - - @Test - @DisplayName("a platform cancellation disposes the reactive subscription") - void platformCancellationDisposesTheSubscription() { - GrpcCancellationCoordinator coordinator = - new GrpcCancellationCoordinator(new GrpcCancellationToken()); - AtomicBoolean disposed = new AtomicBoolean(); - - GrpcReactorCancellationBridge.bindPlatformCancellation( - coordinator, () -> disposed.set(true), "document-query"); - coordinator.cancel(GrpcCancellationReason.DEADLINE_EXCEEDED, NOW); - - assertThat(disposed).isTrue(); - } - - @Test - @DisplayName("binding a subscription without a name is refused") - void bindingNeedsAnOperationName() { - GrpcCancellationCoordinator coordinator = - new GrpcCancellationCoordinator(new GrpcCancellationToken()); - - assertThatThrownBy( - () -> - GrpcReactorCancellationBridge.bindPlatformCancellation(coordinator, () -> {}, " ")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityTest.java b/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityTest.java deleted file mode 100644 index a34f687b..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityTest.java +++ /dev/null @@ -1,180 +0,0 @@ -package dev.caskeleton.grpc.advanced.compat; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.web.GrpcWebProfile; -import dev.caskeleton.grpc.advanced.web.GrpcWebProxyContract; -import dev.caskeleton.grpc.advanced.web.GrpcWebRpcSupport; -import dev.caskeleton.grpc.core.RpcType; -import dev.caskeleton.grpc.error.GrpcErrorMapper; -import dev.caskeleton.grpc.validation.GrpcValidationInterceptor; -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -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; - -class GrpcWebCompatibilityTest { - - @Test - @DisplayName("gRPC-Web carries unary and server streaming, and nothing else") - void grpcWebCarriesTwoShapes() { - assertThat(GrpcWebRpcSupport.supported(RpcType.UNARY)).isTrue(); - assertThat(GrpcWebRpcSupport.supported(RpcType.SERVER_STREAMING)).isTrue(); - assertThat(GrpcWebRpcSupport.supported(RpcType.CLIENT_STREAMING)).isFalse(); - assertThat(GrpcWebRpcSupport.supported(RpcType.BIDI_STREAMING)).isFalse(); - assertThatThrownBy(() -> GrpcWebRpcSupport.require(RpcType.BIDI_STREAMING)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("no way to send a stream of messages"); - } - - @Test - @DisplayName("a wildcard origin is refused, and cookie credentials require CSRF protection") - void browserCredentialRulesDifferByStyle() { - assertThatThrownBy( - () -> - new GrpcWebProfile(GrpcWebProfile.CredentialStyle.BEARER, Set.of("*"), false, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("ambient credentials"); - assertThatThrownBy( - () -> - new GrpcWebProfile( - GrpcWebProfile.CredentialStyle.COOKIE, - Set.of("https://app.example.com"), - false, - true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("CSRF defence is not optional"); - assertThat(GrpcWebProfile.bearer("https://app.example.com").csrfProtection()).isFalse(); - } - - @Test - @DisplayName("a credentialed profile needs an origin allowlist and TLS at the proxy") - void aCredentialedProfileNeedsBoth() { - assertThatThrownBy( - () -> new GrpcWebProfile(GrpcWebProfile.CredentialStyle.BEARER, Set.of(), false, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("origin allowlist"); - assertThatThrownBy( - () -> - new GrpcWebProfile( - GrpcWebProfile.CredentialStyle.BEARER, - Set.of("https://app.example.com"), - false, - false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("TLS terminated at the proxy"); - } - - @Test - @DisplayName("a proxy that hides the status trailers is reported") - void aProxyMustExposeTheStatusTrailers() { - GrpcWebProfile profile = GrpcWebProfile.bearer("https://app.example.com"); - - assertThat( - GrpcWebProxyContract.violations( - profile, Set.of("grpc-status"), Set.of("https://app.example.com"))) - .anySatisfy(violation -> assertThat(violation).contains("grpc-message")); - assertThat( - GrpcWebProxyContract.violations( - profile, - GrpcWebProxyContract.requiredExposedHeaders(), - Set.of("https://app.example.com"))) - .isEmpty(); - } - - @Test - @DisplayName("a proxy allowing any origin, or missing the profile's, is reported") - void proxyOriginMismatchesAreReported() { - GrpcWebProfile profile = GrpcWebProfile.bearer("https://app.example.com"); - - assertThat( - GrpcWebProxyContract.violations( - profile, GrpcWebProxyContract.requiredExposedHeaders(), Set.of("*"))) - .anySatisfy(violation -> assertThat(violation).contains("defeats the profile's allowlist")); - assertThat( - GrpcWebProxyContract.violations( - profile, GrpcWebProxyContract.requiredExposedHeaders(), Set.of())) - .anySatisfy(violation -> assertThat(violation).contains("not in the proxy's allowlist")); - } - - @Test - @DisplayName("the reference Envoy configuration exposes the trailers and pins the origin") - void theReferenceProxyConfigurationIsCorrect() { - String envoy = resource("envoy/envoy.yaml"); - - assertThat(envoy) - .contains("expose_headers: \"grpc-status,grpc-message") - .contains("exact: \"https://app.example.com\"") - .contains("envoy.filters.http.grpc_web"); - } - - @Test - void theReferenceProxyExposesEveryTrailerThePlatformSends() { - // when - Set exposed = headerList(resource("envoy/envoy.yaml"), "expose_headers"); - - // then - assertThat(exposed) - .contains( - "grpc-status", - "grpc-message", - "grpc-status-details-bin", - GrpcErrorMapper.REASON_KEY.name(), - GrpcErrorMapper.EXECUTION_ID_KEY.name(), - GrpcErrorMapper.COMPLETION_OUTCOME_KEY.name(), - GrpcValidationInterceptor.VIOLATIONS_KEY.name()); - } - - @Test - void theReferenceProxyLetsTheBrowserSendItsDeadlineAndClientHeaders() { - // when - Set allowed = headerList(resource("envoy/envoy.yaml"), "allow_headers"); - - // then - assertThat(allowed).contains("grpc-timeout", "x-user-agent", "x-grpc-web", "content-type"); - } - - @Test - void theReferenceRouteLeavesStreamLengthToTheCallersDeadline() { - // when - String envoy = resource("envoy/envoy.yaml"); - - // then - assertThat(envoy).contains("timeout: 0s").contains("grpc_timeout_header_max: 0s"); - } - - @Test - void theReferenceProxyTerminatesTlsWithACertificate() { - // when - String envoy = resource("envoy/envoy.yaml"); - - // then - assertThat(envoy).contains("certificate_chain:").contains("private_key:"); - } - - private static Set headerList(String envoy, String field) { - Matcher matcher = Pattern.compile(field + ": \"([^\"]*)\"").matcher(envoy); - if (!matcher.find()) { - throw new IllegalStateException("the reference proxy has no " + field); - } - return Set.of(matcher.group(1).split(",")); - } - - private static String resource(String path) { - try (InputStream stream = - GrpcWebCompatibilityTest.class.getClassLoader().getResourceAsStream(path)) { - if (stream == null) { - throw new IllegalStateException("missing resource " + path); - } - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml b/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml deleted file mode 100644 index ae3cab3a..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml +++ /dev/null @@ -1,80 +0,0 @@ -# The gRPC-Web proxy contract, as a reference Envoy configuration. -# -# Shipped as a resource rather than as documentation prose because GrpcWebProxyContract asserts -# against it: the CORS allowlist, the exposed trailer headers and the TLS termination are the three -# things a browser client silently fails without, and a contract nobody checks is a contract that -# drifts from whatever is actually deployed. -# -# The exposed headers matter most and are the least obvious. gRPC statuses arrive as trailers, and a -# browser cannot read a trailer the proxy did not expose; the symptom is a call that appears to hang -# and then fails with no status at all. -static_resources: - listeners: - - name: grpc_web_listener - address: - socket_address: { address: 0.0.0.0, port_value: 8443 } - filter_chains: - - filters: - - name: envoy.filters.network.http_connection_manager - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager - stat_prefix: grpc_web - codec_type: AUTO - route_config: - name: grpc_web_route - virtual_hosts: - - name: grpc_web_host - domains: ["*"] - routes: - - match: { prefix: "/" } - route: - cluster: grpc_backend - # No route timeout: it would cut every server stream at that age. The - # caller's grpc-timeout header bounds each call instead. - timeout: 0s - max_stream_duration: - grpc_timeout_header_max: 0s - cors: - allow_origin_string_match: - - exact: "https://app.example.com" - allow_methods: "POST,OPTIONS" - allow_headers: "content-type,x-grpc-web,x-user-agent,grpc-timeout,x-correlation-id,authorization" - # Every trailer the platform sends (GrpcErrorMapper, GrpcValidationInterceptor). - expose_headers: "grpc-status,grpc-message,grpc-status-details-bin,error-reason,error-execution-id,completion-outcome,validation-violations" - max_age: "1728000" - http_filters: - - name: envoy.filters.http.grpc_web - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.http.grpc_web.v3.GrpcWeb - - name: envoy.filters.http.cors - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors - - name: envoy.filters.http.router - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router - transport_socket: - name: envoy.transport_sockets.tls - typed_config: - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext - # Placeholder paths: mount the proxy's certificate and key here. - common_tls_context: - tls_certificates: - - certificate_chain: { filename: /etc/envoy/tls/tls.crt } - private_key: { filename: /etc/envoy/tls/tls.key } - clusters: - - name: grpc_backend - connect_timeout: 1s - type: STRICT_DNS - lb_policy: ROUND_ROBIN - typed_extension_protocol_options: - envoy.extensions.upstreams.http.v3.HttpProtocolOptions: - "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions - explicit_http_config: - http2_protocol_options: {} - load_assignment: - cluster_name: grpc_backend - endpoints: - - lb_endpoints: - - endpoint: - address: - socket_address: { address: documents, port_value: 9090 } diff --git a/src/platforms/grpc-advanced/grpc-advanced/build.gradle b/src/platforms/grpc-advanced/grpc-advanced/build.gradle deleted file mode 100644 index c4b9a188..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/build.gradle +++ /dev/null @@ -1,28 +0,0 @@ -plugins { - // grpc-platform, not platform: grpc-runtime's io.grpc api dependencies are versionless and - // need the gRPC BOM on every classpath they reach. - id 'ca.grpc-platform-module' -} - -// The capabilities the Stable platform deliberately excludes, each behind its own capability flag: -// -// bootstrap capability grades, the `app.grpc.advanced.*` feature-flag contract, the -// module guard that refuses an unflagged capability, the per-capability promotion -// gate -// edition Protobuf Edition 2024 opt-in lane and Edition 2026 watch lane -// streaming client streaming sessions (dedup/checkpoint/resume), bidirectional sessions with -// independent per-direction sequences, the manual flow-control approval API -// resilience read-only unary hedging, custom name resolver / load balancer SPIs, proxyless xDS -// diagnostics Channelz/CSDS snapshots and the redactor that keeps secrets out of them -// -// These were five leaves until 2026-09-28. None of them carried a framework dependency of its own, -// and the only rule the split enforced — Stable never reaches Advanced — is expressed by the -// registry through the two prefixes (`grpc:*` may not depend on `grpc-advanced:*`), not by how many -// advanced leaves exist. `grpc-advanced-compat` stays separate because Reactor and Spring -// Integration are a real dependency boundary. -// -// This leaf depends on Stable public types and never the other way round. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-runtime') -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/gradle.lockfile b/src/platforms/grpc-advanced/grpc-advanced/gradle.lockfile deleted file mode 100644 index d901154b..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/gradle.lockfile +++ /dev/null @@ -1,85 +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,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -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.50.0=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -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,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -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.grpc:grpc-api:1.75.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.grpc:grpc-stub:1.75.0=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.mojo:animal-sniffer-annotations:1.24=compileClasspath,runtimeClasspath,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.6.1=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,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 -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.20=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.20=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java deleted file mode 100644 index 12e8fb65..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.grpc.advanced.bootstrap; - -/** - * Every capability the Stable platform deliberately excludes, and how ready each one is. - * - *

Grading them individually is the design. Bundling them under one "advanced" flag makes - * enabling gRPC-Web — a compatibility bridge with a proxy in front of it — the same decision as - * enabling xDS, which brings a control plane and its outage modes. They are not the same decision, - * and a single switch is how the second one gets made by accident. - */ -public enum GrpcAdvancedCapability { - /** Protobuf Edition 2024 as an opt-in schema lane. */ - EDITION_2024("edition-2024", GrpcCapabilityGrade.ADVANCED_STABLE), - /** Protobuf Edition 2026. Recorded, not usable. */ - EDITION_2026("edition-2026", GrpcCapabilityGrade.WATCH), - /** Client streaming with session, dedup and checkpoint. */ - CLIENT_STREAMING("client-streaming", GrpcCapabilityGrade.ADVANCED_STABLE), - /** Bidirectional streaming with independent per-direction sequences. */ - BIDI_STREAMING("bidi-streaming", GrpcCapabilityGrade.ADVANCED_STABLE), - /** Manual flow control, for approved streaming methods. */ - MANUAL_FLOW_CONTROL("manual-flow-control", GrpcCapabilityGrade.ADVANCED_STABLE), - /** Read-only unary hedging. */ - HEDGING("hedging", GrpcCapabilityGrade.EXPERIMENTAL), - /** A custom name resolver. */ - CUSTOM_RESOLVER("custom-resolver", GrpcCapabilityGrade.ADVANCED_STABLE), - /** A custom load balancer. */ - CUSTOM_LOAD_BALANCER("custom-load-balancer", GrpcCapabilityGrade.EXPERIMENTAL), - /** Proxyless xDS. */ - XDS("xds", GrpcCapabilityGrade.EXPERIMENTAL), - /** The gRPC-Web bridge. */ - GRPC_WEB("grpc-web", GrpcCapabilityGrade.ADVANCED_STABLE), - /** A Servlet container owning the HTTP/2 socket. */ - SERVLET_COMPAT("servlet-compat", GrpcCapabilityGrade.ADVANCED_STABLE), - /** The Spring Integration bridge. */ - INTEGRATION_BRIDGE("integration-bridge", GrpcCapabilityGrade.ADVANCED_STABLE), - /** The Reactor adapter. */ - REACTOR("reactor", GrpcCapabilityGrade.ADVANCED_STABLE), - /** The Kotlin coroutine and Flow adapter. */ - KOTLIN("kotlin", GrpcCapabilityGrade.ADVANCED_STABLE), - /** Channelz and CSDS diagnostics. */ - CHANNEL_DIAGNOSTICS("channel-diagnostics", GrpcCapabilityGrade.ADVANCED_STABLE); - - private final String flagName; - private final GrpcCapabilityGrade defaultGrade; - - GrpcAdvancedCapability(String flagName, GrpcCapabilityGrade defaultGrade) { - this.flagName = flagName; - this.defaultGrade = defaultGrade; - } - - /** The property suffix under {@code app.grpc.advanced}. */ - public String flagName() { - return flagName; - } - - /** The full property key that enables this capability. */ - public String propertyKey() { - return "app.grpc.advanced." + flagName + ".enabled"; - } - - /** How ready this capability is today. */ - public GrpcCapabilityGrade defaultGrade() { - return defaultGrade; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapabilityDisabledException.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapabilityDisabledException.java deleted file mode 100644 index 8a5eb019..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapabilityDisabledException.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.grpc.advanced.bootstrap; - -/** - * A capability was used without being enabled. - * - *

The message carries the property key. An advanced capability is off by default and the refusal - * is the first thing a developer meets when trying it; telling them which key to set turns a - * support question into a configuration line. - */ -public class GrpcAdvancedCapabilityDisabledException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient GrpcAdvancedCapability capability; - - /** Refuses use of a disabled capability. */ - public GrpcAdvancedCapabilityDisabledException(GrpcAdvancedCapability capability, String reason) { - super(render(capability, reason)); - this.capability = capability; - } - - private static String render(GrpcAdvancedCapability capability, String reason) { - if (capability == null) { - throw new IllegalArgumentException("a capability is required"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException("a refusal explains itself"); - } - return "advanced capability '" - + capability.flagName() - + "' is not available: " - + reason - + " (set " - + capability.propertyKey() - + "=true to enable it)"; - } - - /** The capability that was refused. */ - public GrpcAdvancedCapability capability() { - return capability; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedFeatureFlags.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedFeatureFlags.java deleted file mode 100644 index 911063e7..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedFeatureFlags.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.grpc.advanced.bootstrap; - -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.Map; -import java.util.Set; - -/** - * Which advanced capabilities a deployment has turned on. - * - *

Everything is off unless named. A capability that switches itself on because its jar is - * present is a capability nobody decided to run, and the ones here bring proxies, control planes - * and duplicate request load with them. - */ -public final class GrpcAdvancedFeatureFlags { - - private final Map enabled = - new EnumMap<>(GrpcAdvancedCapability.class); - private final Map grades = - new EnumMap<>(GrpcAdvancedCapability.class); - private final boolean production; - private final Set productionApprovals; - - private GrpcAdvancedFeatureFlags( - boolean production, Set productionApprovals) { - this.production = production; - this.productionApprovals = - EnumSet.copyOf( - productionApprovals.isEmpty() - ? EnumSet.noneOf(GrpcAdvancedCapability.class) - : EnumSet.copyOf(productionApprovals)); - for (GrpcAdvancedCapability capability : GrpcAdvancedCapability.values()) { - enabled.put(capability, false); - grades.put(capability, capability.defaultGrade()); - } - } - - /** Flags for a non-production environment. */ - public static GrpcAdvancedFeatureFlags forDevelopment() { - return new GrpcAdvancedFeatureFlags(false, Set.of()); - } - - /** - * Flags for production. - * - * @param productionApprovals the experimental capabilities somebody has accepted the risk of - */ - public static GrpcAdvancedFeatureFlags forProduction( - Set productionApprovals) { - if (productionApprovals == null) { - throw new IllegalArgumentException("an approval set is required, even if empty"); - } - return new GrpcAdvancedFeatureFlags(true, productionApprovals); - } - - /** Turns a capability on. */ - public GrpcAdvancedFeatureFlags enable(GrpcAdvancedCapability capability) { - if (capability == null) { - throw new IllegalArgumentException("a capability is required"); - } - enabled.put(capability, true); - return this; - } - - /** Overrides a capability's grade, for a deployment that has its own evidence. */ - public GrpcAdvancedFeatureFlags withGrade( - GrpcAdvancedCapability capability, GrpcCapabilityGrade grade) { - if (capability == null || grade == null) { - throw new IllegalArgumentException("a grade override needs both parts"); - } - grades.put(capability, grade); - return this; - } - - /** Whether the flag is set, regardless of whether the capability may actually start. */ - public boolean flagSet(GrpcAdvancedCapability capability) { - return Boolean.TRUE.equals(enabled.get(capability)); - } - - /** The grade in force for a capability. */ - public GrpcCapabilityGrade gradeOf(GrpcAdvancedCapability capability) { - return grades.get(capability); - } - - /** Whether this deployment is production. */ - public boolean production() { - return production; - } - - /** Whether an experimental capability has been separately approved for production. */ - public boolean productionApproved(GrpcAdvancedCapability capability) { - return productionApprovals.contains(capability); - } - - /** The capabilities that are both flagged and permitted to start. */ - public Set active() { - Set running = EnumSet.noneOf(GrpcAdvancedCapability.class); - for (GrpcAdvancedCapability capability : GrpcAdvancedCapability.values()) { - if (GrpcAdvancedModuleGuard.available(this, capability)) { - running.add(capability); - } - } - return Set.copyOf(running); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java deleted file mode 100644 index 6d82779b..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.grpc.advanced.bootstrap; - -/** - * The single gate every advanced capability passes through. - * - *

Three conditions, checked in this order because each explains a different refusal: the flag is - * not set, the grade cannot start at all, or production has not separately approved an experimental - * capability. Collapsing them into one boolean produces a "not enabled" message for three - * situations with three different remedies. - */ -public final class GrpcAdvancedModuleGuard { - - private GrpcAdvancedModuleGuard() {} - - /** Whether {@code capability} may run under {@code flags}. */ - public static boolean available( - GrpcAdvancedFeatureFlags flags, GrpcAdvancedCapability capability) { - if (flags == null || capability == null) { - throw new IllegalArgumentException("availability needs flags and a capability"); - } - if (!flags.flagSet(capability)) { - return false; - } - GrpcCapabilityGrade grade = flags.gradeOf(capability); - if (!grade.startable()) { - return false; - } - return !(flags.production() - && grade.requiresProductionApproval() - && !flags.productionApproved(capability)); - } - - /** - * Fails when {@code capability} may not run. - * - * @throws GrpcAdvancedCapabilityDisabledException naming which of the three conditions failed - */ - public static void require(GrpcAdvancedFeatureFlags flags, GrpcAdvancedCapability capability) { - if (flags == null || capability == null) { - throw new IllegalArgumentException("a guard needs flags and a capability"); - } - if (!flags.flagSet(capability)) { - throw new GrpcAdvancedCapabilityDisabledException(capability, "its feature flag is not set"); - } - GrpcCapabilityGrade grade = flags.gradeOf(capability); - if (!grade.startable()) { - throw new GrpcAdvancedCapabilityDisabledException( - capability, - "it is graded " - + grade - + ", which cannot start; a WATCH capability is tracked rather than implemented"); - } - if (flags.production() - && grade.requiresProductionApproval() - && !flags.productionApproved(capability)) { - throw new GrpcAdvancedCapabilityDisabledException( - capability, - "it is " - + grade - + " and production needs a separate approval; the flag says somebody wanted it, not " - + "that somebody accepted its uncharacterised failure modes"); - } - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcCapabilityGrade.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcCapabilityGrade.java deleted file mode 100644 index d97574ce..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcCapabilityGrade.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.grpc.advanced.bootstrap; - -/** - * How much a capability has been established, and what that permits. - * - *

{@link #EXPERIMENTAL} in production needs a second, separate approval rather than the - * capability flag alone. The flag says somebody wanted the feature; the approval says somebody - * accepted that its failure modes are not fully characterised, which is a different person's - * decision on most teams. - */ -public enum GrpcCapabilityGrade { - /** Contract, fault and operational evidence exist. Enable with the capability flag. */ - ADVANCED_STABLE(true, false), - /** Works, but its failure modes are not fully characterised. Needs a production approval too. */ - EXPERIMENTAL(true, true), - /** Tracked, not implemented. Cannot be enabled. */ - WATCH(false, false), - /** Withdrawn or refused. Cannot be enabled. */ - DISABLED(false, false); - - private final boolean startable; - private final boolean requiresProductionApproval; - - GrpcCapabilityGrade(boolean startable, boolean requiresProductionApproval) { - this.startable = startable; - this.requiresProductionApproval = requiresProductionApproval; - } - - /** Whether a deployment may run this capability at all. */ - public boolean startable() { - return startable; - } - - /** Whether production additionally requires an explicit approval. */ - public boolean requiresProductionApproval() { - return requiresProductionApproval; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicy.java deleted file mode 100644 index 2ff22e4a..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicy.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.grpc.advanced.diagnostics; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedFeatureFlags; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedModuleGuard; -import java.util.Set; - -/** - * Who may read diagnostics, and which services are registered at all. - * - *

CSDS is registered only when xDS is enabled. A CSDS service on a deployment that does not use - * xDS answers every query with nothing, which is harmless, and advertises a control-plane surface - * that does not exist, which is not: it is one more endpoint to scan and one more thing whose - * absence of authorization nobody notices. - */ -public record GrpcChannelDiagnosticsPolicy(Set adminNetworks, Set adminRoles) { - - /** Refuses a policy with only one gate. */ - public GrpcChannelDiagnosticsPolicy { - if (adminNetworks == null || adminRoles == null) { - throw new IllegalArgumentException("a diagnostics policy states both gates"); - } - adminNetworks = Set.copyOf(adminNetworks); - adminRoles = Set.copyOf(adminRoles); - if (adminNetworks.isEmpty() || adminRoles.isEmpty()) { - throw new IllegalArgumentException( - "diagnostics need both a network and a role gate; Channelz holds every socket's peer and " - + "security detail, so either gate alone is the whole surface"); - } - } - - /** This repository's default. */ - public static GrpcChannelDiagnosticsPolicy standard() { - return new GrpcChannelDiagnosticsPolicy(Set.of("admin"), Set.of("ROLE_PLATFORM_ADMIN")); - } - - /** Whether this caller may read a snapshot. */ - public boolean mayRead(String callerNetwork, Set callerRoles) { - return callerNetwork != null - && adminNetworks.contains(callerNetwork) - && callerRoles != null - && callerRoles.stream().anyMatch(adminRoles::contains); - } - - /** Whether the Channelz service should be registered. */ - public static boolean registerChannelz(GrpcAdvancedFeatureFlags flags) { - return GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.CHANNEL_DIAGNOSTICS); - } - - /** Whether the CSDS service should be registered. Only when xDS is actually in use. */ - public static boolean registerCsds(GrpcAdvancedFeatureFlags flags) { - return registerChannelz(flags) - && GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.XDS); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsSnapshot.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsSnapshot.java deleted file mode 100644 index a99baef3..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsSnapshot.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.grpc.advanced.diagnostics; - -import java.time.Instant; -import java.util.List; -import java.util.Map; - -/** - * What Channelz and CSDS report, after redaction. - * - *

Counters and states rather than call contents. The questions a diagnostics endpoint exists to - * answer — which subchannels are connected, how many calls are in flight, which xDS resources the - * control plane last sent — are all answerable from aggregates, and aggregates cannot leak a - * caller's data. - */ -public record GrpcChannelDiagnosticsSnapshot( - String channelProfile, - String connectivityState, - int subchannelCount, - long callsStarted, - long callsSucceeded, - long callsFailed, - List maskedSocketAddresses, - Map xdsResourceVersions, - Instant capturedAt) { - - /** Refuses a snapshot carrying something it should not. */ - public GrpcChannelDiagnosticsSnapshot { - if (channelProfile == null || channelProfile.isBlank()) { - throw new IllegalArgumentException("a diagnostics snapshot names its channel profile"); - } - if (connectivityState == null || connectivityState.isBlank()) { - throw new IllegalArgumentException("a diagnostics snapshot carries a connectivity state"); - } - if (subchannelCount < 0 || callsStarted < 0 || callsSucceeded < 0 || callsFailed < 0) { - throw new IllegalArgumentException("diagnostics counters must not be negative"); - } - if (maskedSocketAddresses == null || xdsResourceVersions == null || capturedAt == null) { - throw new IllegalArgumentException("every snapshot section must be present"); - } - maskedSocketAddresses = List.copyOf(maskedSocketAddresses); - xdsResourceVersions = Map.copyOf(xdsResourceVersions); - - maskedSocketAddresses.stream() - .filter(address -> !address.equals(GrpcDiagnosticsRedactor.maskAddress(address))) - .findFirst() - .ifPresent( - unmasked -> { - throw new IllegalArgumentException( - "socket address '" - + unmasked - + "' is not masked; a diagnostics endpoint that publishes peer addresses " - + "publishes every tenant's connection"); - }); - xdsResourceVersions.keySet().stream() - .filter(GrpcDiagnosticsRedactor::forbiddenField) - .findFirst() - .ifPresent( - forbidden -> { - throw new IllegalArgumentException( - "field '" + forbidden + "' may not appear in a diagnostics snapshot"); - }); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactor.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactor.java deleted file mode 100644 index 86a142ea..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactor.java +++ /dev/null @@ -1,107 +0,0 @@ -package dev.caskeleton.grpc.advanced.diagnostics; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Removes from a diagnostics snapshot everything that is not a diagnostic. - * - *

Channelz is unusually dangerous to expose because it is genuinely useful: it holds every - * socket's local and remote address, the security details of each connection, and per-call state. - * An administrator debugging a routing problem needs the shape of that; nobody needs the peer - * addresses of every tenant's connection, and once the endpoint exists the whole of it is one - * authorization mistake away from being readable. - * - *

Addresses are masked rather than dropped. An operator has to be able to tell two subchannels - * apart, and a stable mask does that without publishing where they point. - */ -public final class GrpcDiagnosticsRedactor { - - private static final Pattern SENSITIVE_FIELD = - Pattern.compile( - "(?i).*(authorization|bearer|password|secret|token|private[_-]?key|certificate|" - + "credential|payload|metadata).*"); - - private static final Pattern IPV4_WITH_PORT = - Pattern.compile("\\b(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(:\\d{1,5})?\\b"); - - /** - * The forms {@link #maskAddress} produces, so masking one of them again returns it unchanged. - * - *

{@code GrpcChannelDiagnosticsSnapshot} decides whether an address is masked by masking it - * and comparing — the only test available to it, since a masked address carries no marker. That - * works only if masking is idempotent, and it was not: {@code 10.4.x.x} has no four numeric - * octets, so it fell through to the hash branch and came back as {@code masked:}. A - * snapshot built from correctly masked addresses was therefore rejected as unmasked. - */ - private static final Pattern ALREADY_MASKED = - Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.x\\.x|masked:[0-9a-f]{16}|unknown"); - - private GrpcDiagnosticsRedactor() {} - - /** Whether a field name may appear in a snapshot at all. */ - public static boolean forbiddenField(String fieldName) { - return fieldName != null && SENSITIVE_FIELD.matcher(fieldName).matches(); - } - - /** - * Masks an address so two of them stay distinguishable without being resolvable. - * - *

The last two octets go; the first two stay, because "which subnet" is a real diagnostic - * question and "which host" is not one the diagnostics endpoint should answer. - * - *

Idempotent: masking an already-masked address returns it. Callers rely on that to ask "is - * this masked?" without a marker byte. - */ - public static String maskAddress(String address) { - if (address == null || address.isBlank()) { - return "unknown"; - } - if (ALREADY_MASKED.matcher(address).matches()) { - return address; - } - var matcher = IPV4_WITH_PORT.matcher(address); - if (matcher.find()) { - return matcher.replaceAll( - matchResult -> matchResult.group(1) + "." + matchResult.group(2) + ".x.x"); - } - return "masked:" + stableAddressToken(address); - } - - private static String stableAddressToken(String address) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(address.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest, 0, 8); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is required by the Java runtime", impossible); - } - } - - /** - * A snapshot map with forbidden fields removed and addresses masked. - * - * @param addressFields which keys hold addresses, since a mask applied to everything would mangle - * version strings and counters - */ - public static Map redact( - Map raw, java.util.Set addressFields) { - if (raw == null || addressFields == null) { - throw new IllegalArgumentException("redaction needs the map and the address field set"); - } - Map redacted = new LinkedHashMap<>(); - raw.forEach( - (key, value) -> { - if (forbiddenField(key)) { - return; - } - redacted.put(key, addressFields.contains(key) ? maskAddress(value) : value); - }); - return Map.copyOf(redacted); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcCustomResolver.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcCustomResolver.java deleted file mode 100644 index d1562d5b..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcCustomResolver.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; - -/** - * A custom name resolver, with the safety rules applied on the way in. - * - *

Everything an update can do wrong is checked here rather than by the listener, because the - * listener is the channel and the channel will believe whatever it is told. Stale revisions and - * empty endpoint sets are dropped rather than propagated, and once closed the resolver accepts - * nothing at all. - */ -public final class GrpcCustomResolver implements AutoCloseable { - - private final String authority; - private final Consumer listener; - private final AtomicReference applied = new AtomicReference<>(); - private final AtomicBoolean closed = new AtomicBoolean(); - - /** Binds a resolver to the authority it resolves and the listener it feeds. */ - public GrpcCustomResolver(String authority, Consumer listener) { - if (authority == null || authority.isBlank()) { - throw new IllegalArgumentException("a resolver names the authority it resolves"); - } - if (listener == null) { - throw new IllegalArgumentException("a resolver needs a listener to deliver updates to"); - } - this.authority = authority; - this.listener = listener; - } - - /** - * Offers an update. - * - * @return the violations that stopped it, empty when it was applied - */ - public List offer(GrpcResolverUpdate update) { - if (closed.get()) { - return List.of( - "the resolver is closed; an update after close resurrects routing for a channel nobody " - + "is using"); - } - List violations = GrpcResolverSafetyPolicy.violations(update, applied.get()); - if (!violations.isEmpty()) { - return violations; - } - applied.set(update.snapshot()); - listener.accept(update); - return List.of(); - } - - /** The snapshot currently in force. */ - public Optional currentSnapshot() { - return Optional.ofNullable(applied.get()); - } - - /** The authority this resolver answers for. */ - public String authority() { - return authority; - } - - /** Whether the resolver has been closed. */ - public boolean closed() { - return closed.get(); - } - - @Override - public void close() { - closed.set(true); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointCandidate.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointCandidate.java deleted file mode 100644 index a7e49167..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointCandidate.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -/** - * One endpoint a picker may choose, described only by what routing is allowed to consider. - * - *

The field list is the allowlist. Health, connectivity, weight and ejection are properties of - * the endpoint; a tenant id or a request field is a property of the caller, and routing on those - * turns a load balancer into a router with an authorization decision buried in it. - */ -public record GrpcEndpointCandidate( - String address, boolean healthy, boolean connected, int weight, boolean ejected) { - - /** Requires an address and a sane weight. */ - public GrpcEndpointCandidate { - if (address == null || address.isBlank()) { - throw new IllegalArgumentException("an endpoint candidate needs an address"); - } - if (weight < 0) { - throw new IllegalArgumentException("a weight must not be negative"); - } - if (weight > 1000) { - throw new IllegalArgumentException( - "a weight above 1000 is a scale nobody can reason about against the others"); - } - } - - /** A healthy, connected endpoint at the default weight. */ - public static GrpcEndpointCandidate ready(String address) { - return new GrpcEndpointCandidate(address, true, true, 100, false); - } - - /** Whether this endpoint may receive a request. */ - public boolean selectable() { - return healthy && connected && !ejected && weight > 0; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointSnapshot.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointSnapshot.java deleted file mode 100644 index e5bb2bd0..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointSnapshot.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -import java.util.List; -import java.util.Set; - -/** - * One resolver update: a monotonic revision and the complete endpoint set at that revision. - * - *

Complete, not a delta. A delta protocol needs both sides to agree on what they last saw, and a - * resolver that reconnects to its discovery source has no way to establish that; a full set at each - * revision makes a missed update harmless. - * - *

The revision is what makes a late update safe to drop. Without it, an update that arrives out - * of order replaces newer endpoints with older ones, and the channel routes to instances that were - * removed. - */ -public record GrpcEndpointSnapshot(long revision, String authority, List endpoints) { - - /** Requires a positive revision, an authority and a non-empty endpoint set. */ - public GrpcEndpointSnapshot { - if (revision < 1) { - throw new IllegalArgumentException("resolver revisions are 1-based; got " + revision); - } - if (authority == null || authority.isBlank()) { - throw new IllegalArgumentException("a snapshot names the authority it resolves"); - } - if (endpoints == null || endpoints.isEmpty()) { - throw new IllegalArgumentException( - "an empty endpoint set is refused; a resolver that reports zero endpoints during its own " - + "outage would take the channel down with it"); - } - if (endpoints.stream().anyMatch(endpoint -> endpoint == null || endpoint.isBlank())) { - throw new IllegalArgumentException("every endpoint must be a non-blank address"); - } - endpoints = List.copyOf(endpoints); - if (Set.copyOf(endpoints).size() != endpoints.size()) { - throw new IllegalArgumentException( - "duplicate endpoints skew a round-robin picker towards whichever address is repeated"); - } - } - - /** Whether this snapshot supersedes {@code other}. */ - public boolean supersedes(GrpcEndpointSnapshot other) { - return other == null || (authority.equals(other.authority()) && revision > other.revision()); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerDecision.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerDecision.java deleted file mode 100644 index 9a02e61e..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerDecision.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -import java.util.Optional; - -/** - * Which endpoint a picker chose, or why it chose none. - * - *

{@link Verdict#DETERMINISTIC_FALLBACK} is separate from {@link Verdict#NO_ENDPOINT_AVAILABLE} - * because they say different things about the picker. The first means custom logic failed and the - * platform took over, which is a defect to fix; the second means there was genuinely nowhere to - * send the request, which is an outage. A picker that reports both the same way hides its own bugs - * inside the backend's. - */ -public record GrpcLoadBalancerDecision( - Verdict verdict, Optional chosen, String reason) { - - /** What the picker decided. */ - public enum Verdict { - /** The picker chose an endpoint. */ - PICKED, - /** The picker failed; the platform chose deterministically instead. */ - DETERMINISTIC_FALLBACK, - /** Nothing was selectable. */ - NO_ENDPOINT_AVAILABLE - } - - /** Requires an endpoint on the two verdicts that have one. */ - public GrpcLoadBalancerDecision { - if (verdict == null || chosen == null) { - throw new IllegalArgumentException("a picker decision has a verdict and the Optional"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException("a picker decision explains itself"); - } - if (verdict == Verdict.NO_ENDPOINT_AVAILABLE && chosen.isPresent()) { - throw new IllegalArgumentException("a decision with no endpoint available carries none"); - } - if (verdict != Verdict.NO_ENDPOINT_AVAILABLE && chosen.isEmpty()) { - throw new IllegalArgumentException("a decision that picked carries the endpoint it picked"); - } - } - - /** The picker's own choice. */ - public static GrpcLoadBalancerDecision picked(GrpcEndpointCandidate endpoint, String reason) { - return new GrpcLoadBalancerDecision(Verdict.PICKED, Optional.of(endpoint), reason); - } - - /** The platform's fallback after a picker failure. */ - public static GrpcLoadBalancerDecision fallback(GrpcEndpointCandidate endpoint, String reason) { - return new GrpcLoadBalancerDecision( - Verdict.DETERMINISTIC_FALLBACK, Optional.of(endpoint), reason); - } - - /** Nothing was selectable. */ - public static GrpcLoadBalancerDecision none(String reason) { - return new GrpcLoadBalancerDecision(Verdict.NO_ENDPOINT_AVAILABLE, Optional.empty(), reason); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerPicker.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerPicker.java deleted file mode 100644 index cf929346..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerPicker.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -import java.util.List; - -/** - * Chooses one endpoint from the candidates the resolver supplied. - * - *

The signature is the safety property. A picker receives a list of candidates and nothing else: - * no request, no metadata, no caller. It therefore cannot route on a tenant, and the rule "business - * data is not a routing input" is enforced by there being no business data to reach. - */ -@FunctionalInterface -public interface GrpcLoadBalancerPicker { - - /** - * Picks an endpoint. - * - * @param candidates the selectable endpoints, never empty - * @return the chosen endpoint, which must be one of {@code candidates} - */ - GrpcEndpointCandidate pick(List candidates); - - /** Round-robin, as the deterministic default and the fallback. */ - static GrpcLoadBalancerPicker roundRobin() { - java.util.concurrent.atomic.AtomicInteger cursor = - new java.util.concurrent.atomic.AtomicInteger(); - return candidates -> candidates.get(Math.floorMod(cursor.getAndIncrement(), candidates.size())); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerSafetyPolicy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerSafetyPolicy.java deleted file mode 100644 index d8c2cca2..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerSafetyPolicy.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -import java.util.List; - -/** - * Runs a custom picker and refuses to let it do something the resolver did not authorise. - * - *

Two rules. A picker may only return an endpoint the resolver supplied, because a picker that - * can invent an address can send a request anywhere; and a picker that throws produces a - * deterministic fallback rather than a failed call, because a picker bug should degrade the - * balancing rather than the availability. - * - *

Weighted and load-aware pickers are not refused here, but the plan requires evidence before - * they ship: {@link #requiresLoadEvidence} names which shapes those are. - */ -public final class GrpcLoadBalancerSafetyPolicy { - - private final GrpcLoadBalancerPicker picker; - private final GrpcLoadBalancerPicker fallback; - - /** Wraps a custom picker with the platform's deterministic fallback. */ - public GrpcLoadBalancerSafetyPolicy(GrpcLoadBalancerPicker picker) { - this(picker, GrpcLoadBalancerPicker.roundRobin()); - } - - /** Wraps a custom picker with an explicit fallback. */ - public GrpcLoadBalancerSafetyPolicy( - GrpcLoadBalancerPicker picker, GrpcLoadBalancerPicker fallback) { - if (picker == null || fallback == null) { - throw new IllegalArgumentException("a safety policy needs a picker and a fallback"); - } - this.picker = picker; - this.fallback = fallback; - } - - /** Picks an endpoint, or explains why none was chosen. */ - public GrpcLoadBalancerDecision pick(List candidates) { - if (candidates == null) { - throw new IllegalArgumentException("a candidate list is required"); - } - List selectable = - candidates.stream().filter(GrpcEndpointCandidate::selectable).toList(); - if (selectable.isEmpty()) { - return GrpcLoadBalancerDecision.none( - "no endpoint is healthy, connected, un-ejected and non-zero weight"); - } - GrpcEndpointCandidate chosen; - try { - chosen = picker.pick(selectable); - } catch (RuntimeException pickerFailure) { - return GrpcLoadBalancerDecision.fallback( - fallback.pick(selectable), - "the custom picker threw (" - + pickerFailure.getClass().getSimpleName() - + "); falling back deterministically rather than failing the call"); - } - if (chosen == null || !selectable.contains(chosen)) { - return GrpcLoadBalancerDecision.fallback( - fallback.pick(selectable), - "the custom picker returned an endpoint the resolver did not supply; a picker that can " - + "invent an address can send a request anywhere"); - } - return GrpcLoadBalancerDecision.picked(chosen, "chosen by the custom picker"); - } - - /** - * Whether a picker of this shape needs performance, fairness and failover evidence before it - * ships. - * - * @param loadAware whether the picker uses reported load or latency - * @param weighted whether the picker uses endpoint weights - */ - public static boolean requiresLoadEvidence(boolean loadAware, boolean weighted) { - return loadAware || weighted; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java deleted file mode 100644 index 95bd0bd1..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * What a custom resolver is allowed to say, and what it may never carry. - * - *

A resolver runs inside the channel and speaks to something outside the deployment. Everything - * it can put into an update is therefore attacker-influenced in the worst case and - * operator-influenced in the ordinary one, so the safety rules are about limiting what an update - * can change: addresses and a validated service config, never a credential and never business - * metadata. - */ -public final class GrpcResolverSafetyPolicy { - - private static final Pattern AUTHORITY = - Pattern.compile("[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\\d{1,5})?"); - - /** The top-level fields of a gRPC service config. Anything else is not policy. */ - private static final Set SERVICE_CONFIG_FIELDS = - Set.of( - "loadBalancingConfig", - "loadBalancingPolicy", - "methodConfig", - "retryThrottling", - "healthCheckConfig"); - - private GrpcResolverSafetyPolicy() {} - - /** - * Every problem with an update, given what was last accepted. - * - * @param lastAccepted the newest snapshot already applied, or null when none has been - * @return an empty list when the update is safe to apply - */ - public static List violations( - GrpcResolverUpdate update, GrpcEndpointSnapshot lastAccepted) { - if (update == null) { - throw new IllegalArgumentException("an update is required"); - } - List violations = new ArrayList<>(); - GrpcEndpointSnapshot snapshot = update.snapshot(); - - if (!AUTHORITY.matcher(snapshot.authority()).matches()) { - violations.add( - "authority '" - + snapshot.authority() - + "' is not a plain host or host:port; a resolver that can change the authority can " - + "change which certificate the channel accepts"); - } - if (!snapshot.supersedes(lastAccepted)) { - violations.add( - "revision " - + snapshot.revision() - + " does not supersede the applied revision " - + (lastAccepted == null ? "none" : lastAccepted.revision()) - + "; applying it would replace newer endpoints with older ones"); - } - update.serviceConfig().ifPresent(config -> serviceConfigViolations(config, violations)); - return List.copyOf(violations); - } - - private static void serviceConfigViolations(Map config, List violations) { - if (!SERVICE_CONFIG_FIELDS.containsAll(config.keySet())) { - violations.add( - "the pushed service config has top-level fields outside " - + SERVICE_CONFIG_FIELDS.stream().sorted().toList() - + "; a resolver supplies addresses and policy, never authentication material"); - } - Object methodConfig = config.get("methodConfig"); - if (methodConfig == null) { - return; - } - if (!(methodConfig instanceof List entries) - || !entries.stream().allMatch(entry -> entry instanceof Map)) { - violations.add("the pushed service config's methodConfig is not a list of objects"); - return; - } - if (entries.stream() - .map(entry -> (Map) entry) - .anyMatch( - entry -> entry.containsKey("retryPolicy") || entry.containsKey("hedgingPolicy"))) { - violations.add( - "the pushed service config sets retryPolicy or hedgingPolicy; retries and hedging are " - + "owned by the platform's method policy catalog, and a resolver that could turn them " - + "on could retry a non-idempotent method from outside the codebase"); - } - } - - /** The service config an update may contribute, once validated. */ - public static Optional> acceptedServiceConfig( - GrpcResolverUpdate update, GrpcEndpointSnapshot lastAccepted) { - return violations(update, lastAccepted).isEmpty() ? update.serviceConfig() : Optional.empty(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java deleted file mode 100644 index d09cf367..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.grpc.advanced.discovery; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; - -/** - * A resolver's report: endpoints, and optionally the service config that goes with them. - * - *

The service config is optional and, when present, is validated as if a human had written it. A - * resolver that can push retry policy is a resolver that can turn on retries for a non-idempotent - * method from outside the codebase, and the fact that a control plane sent it is not evidence that - * anyone reviewed it. - */ -public record GrpcResolverUpdate( - GrpcEndpointSnapshot snapshot, Optional> serviceConfig) { - - /** - * Requires a snapshot and the Optional. The service config is the parsed JSON object, the same - * {@code Map} shape gRPC's {@code NameResolver.Helper.parseServiceConfig} takes; it is - * copied so it cannot change between validation and delivery. - */ - public GrpcResolverUpdate { - if (snapshot == null || serviceConfig == null) { - throw new IllegalArgumentException("a resolver update carries a snapshot and the Optional"); - } - serviceConfig.ifPresent( - config -> { - if (config.isEmpty()) { - throw new IllegalArgumentException( - "a present service config must not be empty; absent and empty are different states"); - } - }); - serviceConfig = - serviceConfig.map(config -> Collections.unmodifiableMap(new LinkedHashMap<>(config))); - } - - /** An update with endpoints only. */ - public static GrpcResolverUpdate endpointsOnly(GrpcEndpointSnapshot snapshot) { - return new GrpcResolverUpdate(snapshot, Optional.empty()); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Policy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Policy.java deleted file mode 100644 index 0ec5f0dd..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Policy.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -import java.util.Set; - -/** - * Where Edition 2024 may be used, and where it may not. - * - *

Module-level opt-in, and never for a public service without a promotion decision. The reason - * is that an edition change is invisible to the schema's owner and consequential for its consumers: - * the wire bytes are usually identical, so nothing fails locally, and the breakage appears in - * whichever consumer's generator handles the edition's features differently. - */ -public record GrpcEdition2024Policy( - Set optedInModules, Set publicServices, boolean promotionApproved) { - - /** The edition this policy governs. */ - public static final String EDITION = "2024"; - - /** Copies both sets and refuses an approval nobody recorded. */ - public GrpcEdition2024Policy { - if (optedInModules == null || publicServices == null) { - throw new IllegalArgumentException("an edition policy states both sets"); - } - optedInModules = Set.copyOf(optedInModules); - publicServices = Set.copyOf(publicServices); - } - - /** The default: nothing opted in, no promotion. */ - public static GrpcEdition2024Policy notAdopted() { - return new GrpcEdition2024Policy(Set.of(), Set.of(), false); - } - - /** Whether {@code moduleId} may use Edition 2024 schema sources. */ - public boolean allowedIn(String moduleId) { - return optedInModules.contains(moduleId); - } - - /** - * Whether {@code serviceName} may move onto Edition 2024. - * - *

False for any public service until a promotion is approved, regardless of module opt-in: the - * opt-in is a build decision and the promotion is a consumer-migration decision. - */ - public boolean serviceMayMove(String serviceName) { - return !publicServices.contains(serviceName) || promotionApproved; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Status.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Status.java deleted file mode 100644 index 2e034498..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Status.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -/** - * The four independent things that have to be true before an edition is usable, tracked separately. - * - *

Separately, because they land at different times and in different projects. An edition can be - * released by the specification while {@code protoc} does not emit it, or emitted while Buf cannot - * lint it, or lintable while the Java runtime does not implement its features. A single "supported - * yes/no" flag collapses four different waiting states into one, and the answer to "what are we - * waiting for" is then nobody's. - */ -public enum GrpcEdition2026Status { - /** Nothing is known yet. */ - UNKNOWN, - /** Announced or drafted, not released. */ - DRAFT, - /** Released by the specification. */ - RELEASED, - /** Supported by the toolchain component in question. */ - SUPPORTED, - /** Explicitly not supported, and not expected to be. */ - UNSUPPORTED; - - /** Whether this status permits use. */ - public boolean usable() { - return this == SUPPORTED; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReport.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReport.java deleted file mode 100644 index 719bd707..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReport.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; - -/** - * What is currently true about Edition 2026 across the four things that gate it. - * - *

Recorded with a date. A watch report without one is indistinguishable from a stale note, and - * the whole purpose of a watch lane is to be re-read later by somebody deciding whether the wait is - * over. - */ -public record GrpcEdition2026WatchReport( - GrpcEdition2026Status specificationStatus, - GrpcEdition2026Status protocStatus, - GrpcEdition2026Status bufStatus, - GrpcEdition2026Status javaRuntimeStatus, - Instant observedAt) { - - /** The edition this report tracks. */ - public static final String EDITION = "2026"; - - /** Requires every status and a date. */ - public GrpcEdition2026WatchReport { - if (specificationStatus == null - || protocStatus == null - || bufStatus == null - || javaRuntimeStatus == null) { - throw new IllegalArgumentException("a watch report records all four statuses"); - } - if (observedAt == null) { - throw new IllegalArgumentException( - "a watch report is dated; without a date it cannot be told from a stale note"); - } - } - - /** Nothing known yet, as of {@code observedAt}. */ - public static GrpcEdition2026WatchReport nothingKnown(Instant observedAt) { - return new GrpcEdition2026WatchReport( - GrpcEdition2026Status.UNKNOWN, - GrpcEdition2026Status.UNKNOWN, - GrpcEdition2026Status.UNKNOWN, - GrpcEdition2026Status.UNKNOWN, - observedAt); - } - - /** What is still missing, named. */ - public List outstanding() { - List waiting = new ArrayList<>(); - if (!specificationStatus.usable()) { - waiting.add("specification is " + specificationStatus); - } - if (!protocStatus.usable()) { - waiting.add("protoc support is " + protocStatus); - } - if (!bufStatus.usable()) { - waiting.add("Buf support is " + bufStatus); - } - if (!javaRuntimeStatus.usable()) { - waiting.add("Java runtime support is " + javaRuntimeStatus); - } - return List.copyOf(waiting); - } - - /** Whether every gate is satisfied. */ - public boolean readyToEvaluate() { - return outstanding().isEmpty(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEditionCompatibilityReport.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEditionCompatibilityReport.java deleted file mode 100644 index 4b655f8d..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEditionCompatibilityReport.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * How an Edition schema compares with its proto3 twin, per consumer toolchain. - * - *

Three comparisons rather than one. Wire compatibility says stored and in-flight messages keep - * decoding; JSON compatibility says a REST transcoder or a browser client keeps working; source - * compatibility says the generated code still compiles. An edition migration can preserve the first - * two and break the third for a language whose generator handles the edition's features differently - * — which is exactly the failure this lane exists to find before a public service moves. - */ -public record GrpcEditionCompatibilityReport( - String editionName, - boolean wireCompatible, - boolean jsonCompatible, - Map sourceCompatibleByToolchain) { - - /** Requires an edition and at least one toolchain result. */ - public GrpcEditionCompatibilityReport { - if (editionName == null || editionName.isBlank()) { - throw new IllegalArgumentException("a compatibility report names its edition"); - } - if (sourceCompatibleByToolchain == null || sourceCompatibleByToolchain.isEmpty()) { - throw new IllegalArgumentException( - "a report with no toolchain result compares nothing; Java alone is not cross-language " - + "evidence"); - } - sourceCompatibleByToolchain = Map.copyOf(sourceCompatibleByToolchain); - } - - /** The toolchains whose generated code stopped compiling. */ - public Set brokenToolchains() { - return sourceCompatibleByToolchain.entrySet().stream() - .filter(entry -> !entry.getValue()) - .map(Map.Entry::getKey) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - } - - /** Every incompatibility, described. */ - public List incompatibilities() { - List problems = new ArrayList<>(); - if (!wireCompatible) { - problems.add( - editionName + " is not wire-compatible with proto3; stored messages would break"); - } - if (!jsonCompatible) { - problems.add( - editionName - + " is not JSON-compatible with proto3; transcoded and browser clients would break"); - } - brokenToolchains().stream() - .sorted() - .forEach( - toolchain -> - problems.add( - editionName - + " generated source does not compile for toolchain '" - + toolchain - + "'")); - return List.copyOf(problems); - } - - /** Whether every comparison passed. */ - public boolean fullyCompatible() { - return incompatibilities().isEmpty(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingBudget.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingBudget.java deleted file mode 100644 index ca391979..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingBudget.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Caps duplicate attempts as a fraction of real traffic. - * - *

Necessary for the same reason a retry budget is, and more urgently. A retry happens after a - * failure; a hedge happens on a call that might have succeeded, so a fleet that hedges without a - * budget doubles its backend load in the steady state and doubles it again the moment latency - * rises. - */ -public final class GrpcHedgingBudget { - - private final long maxTokens; - private final long tokensPerHedge; - private final AtomicLong tokens; - - /** - * A budget that starts full. - * - * @param ratio hedges permitted per completed call, e.g. 0.1 for one hedge in ten - * @param maxTokens how much credit may accumulate, which bounds a burst after a quiet period - */ - public static GrpcHedgingBudget of(double ratio, long maxTokens) { - if (ratio <= 0.0d || ratio > 0.5d) { - throw new IllegalArgumentException( - "a hedging ratio above 0.5 means more than half of all calls are duplicated, which is a " - + "load decision rather than a latency one"); - } - if (maxTokens < 1) { - throw new IllegalArgumentException("a budget needs at least one token"); - } - return new GrpcHedgingBudget(maxTokens, Math.round(1.0d / ratio)); - } - - private GrpcHedgingBudget(long maxTokens, long tokensPerHedge) { - this.maxTokens = maxTokens; - this.tokensPerHedge = tokensPerHedge; - this.tokens = new AtomicLong(maxTokens); - } - - /** Takes the credit for one hedge, if there is any. */ - public boolean tryConsume() { - while (true) { - long observed = tokens.get(); - if (observed < tokensPerHedge) { - return false; - } - if (tokens.compareAndSet(observed, observed - tokensPerHedge)) { - return true; - } - } - } - - /** Records a completed call, which earns credit back. */ - public void recordCompletion() { - tokens.updateAndGet(observed -> Math.min(maxTokens, observed + 1L)); - } - - /** How much credit is left. */ - public long availableTokens() { - return tokens.get(); - } - - /** Whether another hedge could be afforded. */ - public boolean exhausted() { - return tokens.get() < tokensPerHedge; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibility.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibility.java deleted file mode 100644 index f9ecc17f..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibility.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -import dev.caskeleton.grpc.api.policy.GrpcMethodPolicy; -import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile; -import dev.caskeleton.grpc.core.RpcType; -import dev.caskeleton.grpc.resilience.GrpcRetryOwner; -import java.util.Optional; - -/** - * Whether a method may be hedged at all. - * - *

Read-only unary, and nothing else. A hedged mutation runs twice by design rather than by - * accident — both attempts are in flight, both may reach the server, and an idempotency key does - * not help because the second attempt is not a retry of a failure but a duplicate of a success in - * progress. A hedged stream is worse still: two streams deliver two prefixes. - */ -public final class GrpcHedgingEligibility { - - private GrpcHedgingEligibility() {} - - /** - * Why {@code policy} may not be hedged, or empty when it may. - * - * @return a refusal reason, or empty when hedging is permitted - */ - public static Optional refusalReason(GrpcMethodPolicy policy, GrpcRetryOwner retryOwner) { - if (policy == null || retryOwner == null) { - throw new IllegalArgumentException("eligibility needs a method policy and a retry owner"); - } - if (policy.rpcType() != RpcType.UNARY) { - return Optional.of( - "method '" - + policy.method().canonical() - + "' is " - + policy.rpcType() - + "; two hedged streams deliver two prefixes"); - } - if (policy.idempotency() != RpcIdempotencyProfile.READ_ONLY) { - return Optional.of( - "method '" - + policy.method().canonical() - + "' is " - + policy.idempotency() - + "; a hedged mutation runs twice by design, and an idempotency key does not help " - + "because the second attempt duplicates a success in progress rather than retrying a " - + "failure"); - } - if (!retryOwner.permitsHedging()) { - return Optional.of( - "retry owner is " + retryOwner + ", which does not permit in-process hedging"); - } - return Optional.empty(); - } - - /** Whether {@code policy} may be hedged. */ - public static boolean eligible(GrpcMethodPolicy policy, GrpcRetryOwner retryOwner) { - return refusalReason(policy, retryOwner).isEmpty(); - } - - /** - * Fails when a method may not be hedged. - * - * @throws IllegalStateException with the reason - */ - public static void require(GrpcMethodPolicy policy, GrpcRetryOwner retryOwner) { - refusalReason(policy, retryOwner) - .ifPresent( - reason -> { - throw new IllegalStateException("hedging refused: " + reason); - }); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingPolicy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingPolicy.java deleted file mode 100644 index 55b34e99..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingPolicy.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -import java.time.Duration; - -/** - * Duplicate in-flight attempts for a read, and the two bounds that keep them affordable. - * - *

Hedging trades backend load for tail latency: a second attempt goes out before the first has - * failed, so a slow replica stops mattering. The cost is that every hedged call may cost two, and - * it costs two precisely when the backend is already slow — which is why the attempt cap starts at - * 2 and the delay is required to be meaningfully above the median. - */ -public record GrpcHedgingPolicy(int maxAttempts, Duration hedgingDelay, Duration totalDeadline) { - - /** The initial cap. Raising it is a deliberate decision with load evidence behind it. */ - public static final int INITIAL_MAX_ATTEMPTS = 2; - - /** Refuses a policy whose duplicate load is unbounded or whose delay is meaningless. */ - public GrpcHedgingPolicy { - if (maxAttempts < 2) { - throw new IllegalArgumentException("hedging means at least two attempts; got " + maxAttempts); - } - if (maxAttempts > INITIAL_MAX_ATTEMPTS) { - throw new IllegalArgumentException( - "hedging is capped at " - + INITIAL_MAX_ATTEMPTS - + " attempts until load evidence justifies more; each extra attempt multiplies " - + "backend load exactly when the backend is already slow"); - } - if (hedgingDelay == null || hedgingDelay.isNegative()) { - throw new IllegalArgumentException("a hedging delay must be present and non-negative"); - } - if (hedgingDelay.isZero()) { - throw new IllegalArgumentException( - "a zero hedging delay sends every attempt at once, which doubles load for every call " - + "rather than for the slow ones"); - } - if (totalDeadline == null || totalDeadline.isZero() || totalDeadline.isNegative()) { - throw new IllegalArgumentException("hedging needs a total deadline to fit inside"); - } - if (hedgingDelay.compareTo(totalDeadline) >= 0) { - throw new IllegalArgumentException( - "the hedging delay is at or above the total deadline, so the second attempt never starts"); - } - } - - /** A policy that hedges once after {@code hedgingDelay}. */ - public static GrpcHedgingPolicy hedgeOnce(Duration hedgingDelay, Duration totalDeadline) { - return new GrpcHedgingPolicy(INITIAL_MAX_ATTEMPTS, hedgingDelay, totalDeadline); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingResult.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingResult.java deleted file mode 100644 index b09457b3..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingResult.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -import java.time.Duration; - -/** - * What a hedged call cost and what it saved. - * - *

Both numbers, because hedging is a trade and a dashboard that shows only the latency - * improvement makes it look free. {@code duplicateBackendCalls} is what the backend team sees, and - * {@code cancelledLoserAttempts} is how much of that work was thrown away. - */ -public record GrpcHedgingResult( - int attemptsIssued, - int winningAttempt, - int cancelledLoserAttempts, - int duplicateBackendCalls, - Duration observedLatency) { - - /** Requires coherent counts. */ - public GrpcHedgingResult { - if (attemptsIssued < 1) { - throw new IllegalArgumentException("a hedged call issues at least one attempt"); - } - if (winningAttempt < 1 || winningAttempt > attemptsIssued) { - throw new IllegalArgumentException("the winning attempt is one of the attempts issued"); - } - if (cancelledLoserAttempts < 0 || cancelledLoserAttempts > attemptsIssued - 1) { - throw new IllegalArgumentException( - "at most every attempt but the winner can be a cancelled loser"); - } - if (duplicateBackendCalls < 0 || duplicateBackendCalls > attemptsIssued - 1) { - throw new IllegalArgumentException( - "duplicate backend calls are the attempts beyond the first"); - } - if (observedLatency == null || observedLatency.isNegative()) { - throw new IllegalArgumentException("a hedged call records its latency"); - } - } - - /** A call that did not need to hedge. */ - public static GrpcHedgingResult firstAttemptWon(Duration latency) { - return new GrpcHedgingResult(1, 1, 0, 0, latency); - } - - /** Whether this call actually issued a duplicate. */ - public boolean hedged() { - return attemptsIssued > 1; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiDirectionState.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiDirectionState.java deleted file mode 100644 index 26a9afa6..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiDirectionState.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -/** - * One direction of a bidirectional stream, tracked on its own. - * - *

Independently, because the two directions genuinely end at different times: a client that has - * finished sending is still receiving, and a server that has finished sending is still reading. A - * single state for both cannot express either, and the usual symptom is a stream closed while one - * side still had messages to deliver. - */ -public record GrpcBidiDirectionState(long lastSequence, boolean halfClosed, boolean cancelled) { - - /** Requires a non-negative position. */ - public GrpcBidiDirectionState { - if (lastSequence < 0) { - throw new IllegalArgumentException("a direction's sequence is at or after zero"); - } - if (halfClosed && cancelled) { - throw new IllegalArgumentException( - "a direction that was cancelled did not half-close; the two are different endings and a " - + "client acts on them differently"); - } - } - - /** A direction that has sent nothing yet. */ - public static GrpcBidiDirectionState open() { - return new GrpcBidiDirectionState(0L, false, false); - } - - /** - * Records a message at the next sequence. - * - * @throws IllegalStateException when the direction has already ended - */ - public GrpcBidiDirectionState advanced() { - if (halfClosed || cancelled) { - throw new IllegalStateException( - "this direction has already ended; a message after half-close is a protocol error, not a " - + "late arrival"); - } - return new GrpcBidiDirectionState(lastSequence + 1, false, false); - } - - /** Records that this direction will send nothing more. */ - public GrpcBidiDirectionState halfClose() { - if (cancelled) { - throw new IllegalStateException("a cancelled direction cannot half-close"); - } - return new GrpcBidiDirectionState(lastSequence, true, false); - } - - /** Records that this direction was cancelled. */ - public GrpcBidiDirectionState cancel() { - return new GrpcBidiDirectionState(lastSequence, false, true); - } - - /** Whether this direction has finished. */ - public boolean ended() { - return halfClosed || cancelled; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiResumeState.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiResumeState.java deleted file mode 100644 index 68cfbd46..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiResumeState.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -/** - * What a bidirectional resume has to carry: both applied positions, and the generation they belong - * to. - * - *

Both, because a resume that restores one direction and restarts the other produces exactly the - * failure the dual sequence exists to prevent. The generation is checked first: a mismatch means - * the session was restarted rather than resumed, and continuing from either position would be - * meaningless. - */ -public record GrpcBidiResumeState( - GrpcClientStreamSessionId sessionId, long clientAppliedSequence, long serverAppliedSequence) { - - /** Requires a session and two non-negative positions. */ - public GrpcBidiResumeState { - if (sessionId == null) { - throw new IllegalArgumentException("a bidi resume state belongs to a session"); - } - if (clientAppliedSequence < 0 || serverAppliedSequence < 0) { - throw new IllegalArgumentException("applied sequences are at or after zero"); - } - } - - /** - * Whether {@code presented} can continue this session. - * - *

A generation mismatch requires a full restart. The session was re-established rather than - * resumed, so neither side's position refers to the same stream of messages. - */ - public boolean resumableFrom(GrpcClientStreamSessionId presented) { - return presented != null - && sessionId.sameSessionAs(presented) - && presented.generation() == sessionId.generation(); - } - - /** The state after a resume, at the next generation. */ - public GrpcBidiResumeState resumed() { - return new GrpcBidiResumeState( - sessionId.resumed(), clientAppliedSequence, serverAppliedSequence); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTracker.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTracker.java deleted file mode 100644 index b0483dd4..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTracker.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -/** - * Two sequences, one per direction, never merged. - * - *

Merging them is the mistake this class exists to prevent, and it is tempting because one - * counter looks simpler. It is not equivalent: the client's message 5 and the server's message 5 - * are unrelated events, and a shared counter makes a resume token from one side meaningless to the - * other — so a reconnect either skips or replays, depending on which side moved faster. - */ -public final class GrpcBidiSequenceTracker { - - private GrpcBidiDirectionState clientToServer = GrpcBidiDirectionState.open(); - private GrpcBidiDirectionState serverToClient = GrpcBidiDirectionState.open(); - - /** Records a client-to-server message and returns its sequence. */ - public synchronized long nextClientSequence() { - clientToServer = clientToServer.advanced(); - return clientToServer.lastSequence(); - } - - /** Records a server-to-client message and returns its sequence. */ - public synchronized long nextServerSequence() { - serverToClient = serverToClient.advanced(); - return serverToClient.lastSequence(); - } - - /** The client-to-server direction. */ - public synchronized GrpcBidiDirectionState clientToServer() { - return clientToServer; - } - - /** The server-to-client direction. */ - public synchronized GrpcBidiDirectionState serverToClient() { - return serverToClient; - } - - /** Records that the client will send nothing more. */ - public synchronized void halfCloseClient() { - clientToServer = clientToServer.halfClose(); - } - - /** Records that the server will send nothing more. */ - public synchronized void halfCloseServer() { - serverToClient = serverToClient.halfClose(); - } - - /** Cancels one direction without touching the other. */ - public synchronized void cancelClient() { - clientToServer = clientToServer.cancel(); - } - - /** Cancels the server direction without touching the client's. */ - public synchronized void cancelServer() { - serverToClient = serverToClient.cancel(); - } - - /** Whether both directions have ended. */ - public synchronized boolean bothEnded() { - return clientToServer.ended() && serverToClient.ended(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSession.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSession.java deleted file mode 100644 index bc45b52d..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSession.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import dev.caskeleton.grpc.streaming.GrpcFlowControlPolicy; -import java.util.Optional; - -/** - * A bidirectional session: two directions, two queues, two single writers. - * - *

Two of everything, because the two directions have independent producers and independent - * consumers. Sharing a queue between them means the slower direction throttles the faster one; and - * sharing a writer reintroduces the concurrent-{@code onNext} problem the Stable serialized writer - * exists to solve, this time with the two sides of the same call racing each other. - */ -public final class GrpcBidiSession { - - private final GrpcClientStreamSessionId sessionId; - private final GrpcBidiSequenceTracker sequences = new GrpcBidiSequenceTracker(); - private final GrpcFlowControlPolicy inboundFlowControl; - private final GrpcFlowControlPolicy outboundFlowControl; - - /** Opens a session with an independent flow-control policy per direction. */ - public GrpcBidiSession( - GrpcClientStreamSessionId sessionId, - GrpcFlowControlPolicy inboundFlowControl, - GrpcFlowControlPolicy outboundFlowControl) { - if (sessionId == null || inboundFlowControl == null || outboundFlowControl == null) { - throw new IllegalArgumentException( - "a bidi session needs an id and a flow-control policy for each direction"); - } - this.sessionId = sessionId; - this.inboundFlowControl = inboundFlowControl; - this.outboundFlowControl = outboundFlowControl; - } - - /** The session's identity. */ - public GrpcClientStreamSessionId sessionId() { - return sessionId; - } - - /** The sequence tracker. */ - public GrpcBidiSequenceTracker sequences() { - return sequences; - } - - /** The inbound direction's bounds. */ - public GrpcFlowControlPolicy inboundFlowControl() { - return inboundFlowControl; - } - - /** The outbound direction's bounds. */ - public GrpcFlowControlPolicy outboundFlowControl() { - return outboundFlowControl; - } - - /** The resume state as it stands. */ - public GrpcBidiResumeState resumeState() { - return new GrpcBidiResumeState( - sessionId, - sequences.clientToServer().lastSequence(), - sequences.serverToClient().lastSequence()); - } - - /** - * Whether {@code presented} may continue this session, and from where. - * - * @return empty when the generation does not match, which requires a full session restart - */ - public Optional resumeFrom(GrpcClientStreamSessionId presented) { - GrpcBidiResumeState state = resumeState(); - return state.resumableFrom(presented) ? Optional.of(state) : Optional.empty(); - } - - /** Whether the session is finished in both directions. */ - public boolean complete() { - return sequences.bothEnded(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicator.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicator.java deleted file mode 100644 index f7b1b956..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicator.java +++ /dev/null @@ -1,123 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Decides what to do with a client stream message that may have arrived before. - * - *

Checkpoint-based rather than a set of seen keys. A set grows without bound for the life of a - * session and answers "have I seen this" — which is not quite the question. The question is "has - * this been applied", and a monotonic applied-sequence answers it in constant space and survives - * the process restart that a set does not. - * - *

Replayed outcomes are kept for the small window after the checkpoint, so a duplicate that - * arrives before the checkpoint advances gets the original answer rather than being reapplied. - */ -public final class GrpcClientMessageDeduplicator { - - private final ConcurrentMap checkpoints = - new ConcurrentHashMap<>(); - private final ConcurrentMap replayableOutcomes = new ConcurrentHashMap<>(); - - /** What to do with an incoming message. */ - public enum Disposition { - /** Not seen; apply it. */ - APPLY, - /** Already applied; return the stored outcome if there is one, otherwise ignore. */ - REPLAY, - /** Out of order ahead of the checkpoint; the sender skipped something. */ - GAP - } - - /** Starts tracking a session. */ - public void beginSession(GrpcClientStreamSessionId sessionId, Instant at) { - if (sessionId == null || at == null) { - throw new IllegalArgumentException("a session needs an id and a moment"); - } - checkpoints.putIfAbsent(sessionId.value(), GrpcClientStreamCheckpoint.empty(sessionId, at)); - } - - /** - * What to do with {@code message}. - * - * @throws IllegalStateException when the session is not being tracked, which means a message - * arrived for a session the server never opened - */ - public Disposition dispositionOf(GrpcClientStreamMessage message) { - if (message == null) { - throw new IllegalArgumentException("a message is required"); - } - GrpcClientStreamCheckpoint checkpoint = requireCheckpoint(message.sessionId()); - if (checkpoint.alreadyApplied(message.sequence())) { - return Disposition.REPLAY; - } - if (message.sequence() > checkpoint.lastAppliedSequence() + 1) { - return Disposition.GAP; - } - return Disposition.APPLY; - } - - /** - * Records that a message was applied, together with the outcome a duplicate would receive. - * - *

The application effect and this checkpoint belong in one transaction wherever the datastore - * allows it. Committing them separately leaves a window in which the effect is durable and the - * checkpoint is not, and a reconnect in that window reapplies the message. - */ - public void recordApplied( - GrpcClientStreamMessage message, String outcomeReference, Instant at) { - GrpcClientStreamCheckpoint checkpoint = requireCheckpoint(message.sessionId()); - checkpoints.put(message.sessionId().value(), checkpoint.advancedTo(message.sequence(), at)); - if (outcomeReference != null && !outcomeReference.isBlank()) { - replayableOutcomes.put(message.dedupKey(), outcomeReference); - } - } - - /** The stored outcome for a duplicate, when one was recorded. */ - public Optional replayOutcome(GrpcClientStreamMessage message) { - return Optional.ofNullable(replayableOutcomes.get(message.dedupKey())); - } - - /** The checkpoint for a session. */ - public Optional checkpointOf(GrpcClientStreamSessionId sessionId) { - return Optional.ofNullable(checkpoints.get(sessionId.value())); - } - - /** Whether a reconnecting client may continue. */ - public GrpcClientStreamResumeDecision decideResume( - GrpcClientStreamSessionId presented, String presentedCaller, String sessionOwner) { - if (presented == null) { - throw new IllegalArgumentException("a resume needs a presented session"); - } - if (presentedCaller == null || !presentedCaller.equals(sessionOwner)) { - return GrpcClientStreamResumeDecision.reject( - "the presented session belongs to a different caller"); - } - GrpcClientStreamCheckpoint checkpoint = checkpoints.get(presented.value()); - if (checkpoint == null) { - return GrpcClientStreamResumeDecision.newSession( - "the server holds no checkpoint for this session; resuming would leave its prefix either " - + "lost or applied twice, with nothing to tell which"); - } - return GrpcClientStreamResumeDecision.resume( - checkpoint.lastAppliedSequence(), "continuing from the last applied message"); - } - - /** Forgets a finished session. */ - public void endSession(GrpcClientStreamSessionId sessionId) { - checkpoints.remove(sessionId.value()); - replayableOutcomes.keySet().removeIf(key -> key.startsWith(sessionId.value() + "|")); - } - - private GrpcClientStreamCheckpoint requireCheckpoint(GrpcClientStreamSessionId sessionId) { - GrpcClientStreamCheckpoint checkpoint = checkpoints.get(sessionId.value()); - if (checkpoint == null) { - throw new IllegalStateException( - "no session is open for '" + sessionId.value() + "'; call beginSession first"); - } - return checkpoint; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamCheckpoint.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamCheckpoint.java deleted file mode 100644 index c9fc10fa..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamCheckpoint.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import java.time.Instant; - -/** - * How far a client stream's messages have actually been applied. - * - *

Applied, not received. The distinction is the whole contract: the transport acknowledging a - * message means it reached the server's buffer, and a checkpoint means the application committed - * its effect. A resume that continues from a transport acknowledgement skips everything that was - * received and not yet applied when the connection died. - */ -public record GrpcClientStreamCheckpoint( - GrpcClientStreamSessionId sessionId, long lastAppliedSequence, Instant checkpointedAt) { - - /** Requires a session, a non-negative position and a moment. */ - public GrpcClientStreamCheckpoint { - if (sessionId == null) { - throw new IllegalArgumentException("a checkpoint belongs to a session"); - } - if (lastAppliedSequence < 0) { - throw new IllegalArgumentException("an applied sequence is at or after zero"); - } - if (checkpointedAt == null) { - throw new IllegalArgumentException("a checkpoint records when it was taken"); - } - } - - /** A session that has applied nothing yet. */ - public static GrpcClientStreamCheckpoint empty(GrpcClientStreamSessionId sessionId, Instant at) { - return new GrpcClientStreamCheckpoint(sessionId, 0L, at); - } - - /** - * Advances the checkpoint. - * - * @throws IllegalArgumentException when it would go backwards, which means two writers are - * checkpointing the same session - */ - public GrpcClientStreamCheckpoint advancedTo(long appliedSequence, Instant at) { - if (appliedSequence < lastAppliedSequence) { - throw new IllegalArgumentException( - "a checkpoint cannot move backwards from " - + lastAppliedSequence - + " to " - + appliedSequence - + "; two writers are checkpointing one session"); - } - return new GrpcClientStreamCheckpoint(sessionId, appliedSequence, at); - } - - /** Whether a message at {@code sequence} has already been applied. */ - public boolean alreadyApplied(long sequence) { - return sequence <= lastAppliedSequence; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamMessage.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamMessage.java deleted file mode 100644 index 5af58172..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamMessage.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -/** - * One message a client sends, carrying the session and sequence that make it identifiable. - * - *

The sequence is the client's, not the transport's. gRPC guarantees ordering within a stream - * and says nothing about a stream that was re-established; a client that reconnects and resends - * needs its own numbering for the server to tell a resend from a new message. - * - * @param the payload type - */ -public record GrpcClientStreamMessage( - GrpcClientStreamSessionId sessionId, long sequence, T payload) { - - /** Requires a session, a one-based sequence and a payload. */ - public GrpcClientStreamMessage { - if (sessionId == null) { - throw new IllegalArgumentException("a client stream message belongs to a session"); - } - if (sequence < 1) { - throw new IllegalArgumentException("client stream sequences are 1-based; got " + sequence); - } - if (payload == null) { - throw new IllegalArgumentException("a client stream message carries a payload"); - } - } - - /** The dedup key for this message. */ - public String dedupKey() { - return sessionId.dedupKey(sequence); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicy.java deleted file mode 100644 index 90a96b19..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicy.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import java.time.Duration; - -/** - * The bounds a client stream runs under. - * - *

A client stream is an inbound firehose with a single response at the end, so all four bounds - * are about the client rather than the server: how long it may hold the stream, how long it may go - * quiet, how fast it may send, and how much it may have unacknowledged. Without them, one client - * can occupy a server thread indefinitely while sending nothing. - * - *

Whole-stream transparent retry is not a setting. It is refused, because replaying a stream the - * server partially applied applies its prefix twice. - */ -public record GrpcClientStreamPolicy( - Duration maxDuration, Duration idleTimeout, int maxMessagesPerSecond, int maxInFlightMessages) { - - /** Refuses an unbounded client stream. */ - public GrpcClientStreamPolicy { - if (maxDuration == null || maxDuration.isZero() || maxDuration.isNegative()) { - throw new IllegalArgumentException("a client stream needs a maximum duration"); - } - if (idleTimeout == null || idleTimeout.isZero() || idleTimeout.isNegative()) { - throw new IllegalArgumentException("a client stream needs an idle timeout"); - } - if (idleTimeout.compareTo(maxDuration) > 0) { - throw new IllegalArgumentException( - "an idle timeout longer than the max duration never fires"); - } - if (maxMessagesPerSecond < 1 || maxInFlightMessages < 1) { - throw new IllegalArgumentException("message rate and in-flight bounds must be positive"); - } - } - - /** A default for an upload-shaped client stream. */ - public static GrpcClientStreamPolicy standard() { - return new GrpcClientStreamPolicy(Duration.ofMinutes(10), Duration.ofSeconds(30), 500, 64); - } - - /** - * Whether a whole client stream may be transparently retried. - * - *

Always false. A stream whose prefix the server already applied cannot be replayed without - * applying that prefix again, and the transport has no way to know how much was applied. - */ - public boolean wholeStreamRetryAllowed() { - return false; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamResumeDecision.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamResumeDecision.java deleted file mode 100644 index 0a0bd343..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamResumeDecision.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import java.util.Optional; - -/** - * Whether a reconnecting client may continue its session. - * - *

{@link Verdict#NEW_SESSION_REQUIRED} is what a server says when it no longer holds the - * checkpoint. Letting the client resume anyway would mean accepting messages numbered from where it - * thinks it stopped, against a server that has no record of the prefix — so the prefix is either - * lost or applied twice, and nothing detects which. - */ -public record GrpcClientStreamResumeDecision( - Verdict verdict, Optional resumeFromSequence, String reason) { - - /** What the server decided. */ - public enum Verdict { - /** Continue from the checkpoint. */ - RESUME, - /** The session is gone; start a new one and resend everything. */ - NEW_SESSION_REQUIRED, - /** The presented session does not belong to this caller. */ - REJECTED - } - - /** Requires a sequence only on RESUME. */ - public GrpcClientStreamResumeDecision { - if (verdict == null || resumeFromSequence == null) { - throw new IllegalArgumentException( - "a resume decision has a verdict and the sequence Optional"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException("a resume decision explains itself"); - } - if (verdict == Verdict.RESUME && resumeFromSequence.isEmpty()) { - throw new IllegalArgumentException("a RESUME decision says where to continue from"); - } - if (verdict != Verdict.RESUME && resumeFromSequence.isPresent()) { - throw new IllegalArgumentException("only a RESUME decision carries a sequence"); - } - } - - /** Continue from {@code sequence}. */ - public static GrpcClientStreamResumeDecision resume(long sequence, String reason) { - return new GrpcClientStreamResumeDecision(Verdict.RESUME, Optional.of(sequence), reason); - } - - /** Start over. */ - public static GrpcClientStreamResumeDecision newSession(String reason) { - return new GrpcClientStreamResumeDecision( - Verdict.NEW_SESSION_REQUIRED, Optional.empty(), reason); - } - - /** Refuse the presented session. */ - public static GrpcClientStreamResumeDecision reject(String reason) { - return new GrpcClientStreamResumeDecision(Verdict.REJECTED, Optional.empty(), reason); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamSessionId.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamSessionId.java deleted file mode 100644 index 1292ed34..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamSessionId.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import java.util.UUID; - -/** - * A client stream's identity, plus the generation a reconnect advances. - * - *

The generation is what makes dedup possible across a reconnect. Message 7 of generation 1 and - * message 7 of generation 2 are different messages; a dedup key that ignores the generation drops - * the second, and the caller's seventh message is silently never applied. - */ -public record GrpcClientStreamSessionId(String value, long generation) { - - /** Requires a bounded id and a positive generation. */ - public GrpcClientStreamSessionId { - if (value == null || value.isBlank() || value.length() > 64) { - throw new IllegalArgumentException("a session id is a bounded non-blank identifier"); - } - if (generation < 1) { - throw new IllegalArgumentException("session generations are 1-based; got " + generation); - } - } - - /** A fresh session. */ - public static GrpcClientStreamSessionId newSession() { - return new GrpcClientStreamSessionId(UUID.randomUUID().toString(), 1L); - } - - /** The same session, resumed. */ - public GrpcClientStreamSessionId resumed() { - return new GrpcClientStreamSessionId(value, generation + 1); - } - - /** Whether {@code other} is the same logical session in any generation. */ - public boolean sameSessionAs(GrpcClientStreamSessionId other) { - return other != null && value.equals(other.value()); - } - - /** The dedup key for a message at {@code sequence} in this generation. */ - public String dedupKey(long sequence) { - if (sequence < 1) { - throw new IllegalArgumentException("client stream sequences are 1-based"); - } - return value + "|" + generation + "|" + sequence; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamState.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamState.java deleted file mode 100644 index 17f64966..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamState.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -/** - * Where a client stream is in its life. - * - *

{@link #HALF_CLOSED} is separate from {@link #COMPLETED} because the server is still working - * between them: the client has said it will send nothing more, and the single response has not - * arrived. A state machine that merges them cannot express "we are waiting for the result of what - * we sent", which is the only interesting moment in a client stream. - */ -public enum GrpcClientStreamState { - /** Accepting messages from the client. */ - OPEN(true), - /** The client has finished sending; the server is producing its response. */ - HALF_CLOSED(false), - /** The server responded. */ - COMPLETED(false), - /** The stream ended without a response. */ - CANCELLED(false); - - private final boolean acceptsMessages; - - GrpcClientStreamState(boolean acceptsMessages) { - this.acceptsMessages = acceptsMessages; - } - - /** Whether another client message may be accepted. */ - public boolean acceptsMessages() { - return acceptsMessages; - } - - /** Whether the stream has finished, one way or another. */ - public boolean terminal() { - return this == COMPLETED || this == CANCELLED; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandController.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandController.java deleted file mode 100644 index e8da26ca..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandController.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import java.time.Duration; -import java.time.Instant; - -/** - * Tracks demand in one direction and refuses to let it grow past its bound. - * - *

Never returns the underlying observer. Handing an application the raw {@code - * ServerCallStreamObserver} gives it {@code request(n)} with no ceiling and {@code onNext} with no - * serialization, which is both bounds gone at once; this controller is what the application talks - * to instead. - * - *

The watchdog compares two moments rather than sleeping: when demand was last requested, and - * when a message last moved. Both stalling for the timeout is the deadlock. - */ -public final class GrpcDemandController { - - private final GrpcManualFlowControlPolicy policy; - private int outstandingDemand; - private Instant lastDemandRequestedAt; - private Instant lastMessageAt; - - /** Starts a controller at {@code startedAt} with no outstanding demand. */ - public GrpcDemandController(GrpcManualFlowControlPolicy policy, Instant startedAt) { - if (policy == null || startedAt == null) { - throw new IllegalArgumentException("a demand controller needs a policy and a start moment"); - } - this.policy = policy; - this.lastDemandRequestedAt = startedAt; - this.lastMessageAt = startedAt; - } - - /** - * Whether more may be requested at {@code now}. - * - * @param peerWaiting whether the other direction is itself blocked waiting for this one - */ - public synchronized GrpcDemandDecision decide(Instant now, boolean peerWaiting) { - if (now == null) { - throw new IllegalArgumentException("a demand decision needs a moment"); - } - if (peerWaiting && stalledFor(now, policy.deadlockWatchdogTimeout())) { - return new GrpcDemandDecision( - GrpcDemandDecision.Action.DEADLOCK_SUSPECTED, - outstandingDemand, - "neither direction has moved for " - + policy.deadlockWatchdogTimeout() - + " while both are waiting; the stream is open and will never progress"); - } - if (outstandingDemand >= policy.maxOutstandingDemand()) { - return new GrpcDemandDecision( - GrpcDemandDecision.Action.HOLD, - outstandingDemand, - "outstanding demand is at its ceiling of " + policy.maxOutstandingDemand()); - } - return new GrpcDemandDecision( - GrpcDemandDecision.Action.REQUEST_MORE, outstandingDemand, "within the demand ceiling"); - } - - /** - * Records a request for {@code count} more messages. - * - * @throws IllegalArgumentException when it would exceed the ceiling - */ - public synchronized void request(int count, Instant now) { - if (count < 1) { - throw new IllegalArgumentException("a demand request is for at least one message"); - } - if (outstandingDemand + count > policy.maxOutstandingDemand()) { - throw new IllegalArgumentException( - "requesting " - + count - + " more would take outstanding demand to " - + (outstandingDemand + count) - + ", above the ceiling of " - + policy.maxOutstandingDemand()); - } - outstandingDemand += count; - lastDemandRequestedAt = now; - } - - /** Records that one message arrived, consuming a unit of demand. */ - public synchronized void messageReceived(Instant now) { - if (outstandingDemand > 0) { - outstandingDemand--; - } - lastMessageAt = now; - } - - /** How much demand is outstanding. */ - public synchronized int outstandingDemand() { - return outstandingDemand; - } - - /** The high-water mark a metric records. */ - public synchronized int demandCeiling() { - return policy.maxOutstandingDemand(); - } - - private boolean stalledFor(Instant now, Duration timeout) { - return !now.isBefore(lastMessageAt.plus(timeout)) - && !now.isBefore(lastDemandRequestedAt.plus(timeout)); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandDecision.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandDecision.java deleted file mode 100644 index 5815b01e..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandDecision.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -/** - * Whether more inbound messages may be requested, or more outbound produced. - * - *

{@link Action#DEADLOCK_SUSPECTED} is a real answer rather than a diagnostic. Manual flow - * control makes it possible for both sides to be waiting for the other, and that state has no - * timeout of its own: the stream is healthy, the connection is open, and nothing will ever move - * again. Naming it is what lets a watchdog end the stream instead of leaking it. - */ -public record GrpcDemandDecision(Action action, int outstandingDemand, String reason) { - - /** What the caller should do. */ - public enum Action { - /** Request more inbound messages, or produce more outbound ones. */ - REQUEST_MORE, - /** Hold: the outstanding demand is already at its bound. */ - HOLD, - /** Neither side can move; end the stream. */ - DEADLOCK_SUSPECTED - } - - /** Requires a reason and a non-negative demand. */ - public GrpcDemandDecision { - if (action == null) { - throw new IllegalArgumentException("a demand decision has an action"); - } - if (outstandingDemand < 0) { - throw new IllegalArgumentException("outstanding demand must not be negative"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException("a demand decision explains itself"); - } - } - - /** Whether the caller may ask for more. */ - public boolean mayRequestMore() { - return action == Action.REQUEST_MORE; - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcManualFlowControlPolicy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcManualFlowControlPolicy.java deleted file mode 100644 index 4903f341..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcManualFlowControlPolicy.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import java.time.Duration; - -/** - * The bounds a manually flow-controlled stream runs under. - * - *

Manual flow control hands the application the {@code request(n)} call, which is exactly the - * knob automatic flow control exists to turn correctly. The two bounds here are what keep that from - * becoming unbounded buffering: a ceiling on outstanding demand, and a watchdog for the state where - * both sides are waiting. - * - *

Approval is a field because this capability is granted per method, not per service. A method - * that reads a large result set benefits; the one next to it does not, and enabling both because - * they share a service is how the second one acquires a bug nobody was looking for. - */ -public record GrpcManualFlowControlPolicy( - int maxOutstandingDemand, Duration deadlockWatchdogTimeout, boolean approvedForMethod) { - - /** Refuses an unapproved or unbounded manual-flow-control policy. */ - public GrpcManualFlowControlPolicy { - if (maxOutstandingDemand < 1) { - throw new IllegalArgumentException( - "manual flow control needs a demand ceiling; without one, request(n) is unbounded " - + "buffering with extra steps"); - } - if (deadlockWatchdogTimeout == null - || deadlockWatchdogTimeout.isZero() - || deadlockWatchdogTimeout.isNegative()) { - throw new IllegalArgumentException( - "manual flow control needs a watchdog; a stream where both sides wait for the other has " - + "no timeout of its own"); - } - if (!approvedForMethod) { - throw new IllegalArgumentException( - "manual flow control is granted per method; an unapproved policy would enable it for " - + "every method on the service"); - } - } - - /** A policy for an approved method. */ - public static GrpcManualFlowControlPolicy forApprovedMethod(int maxOutstandingDemand) { - return new GrpcManualFlowControlPolicy(maxOutstandingDemand, Duration.ofSeconds(30), true); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsFailurePolicy.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsFailurePolicy.java deleted file mode 100644 index 212f0188..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsFailurePolicy.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.grpc.advanced.xds; - -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - -/** - * What happens when the control plane goes away. - * - *

Last-known-good, with a bound. Serving forever from a stale snapshot means a decommissioned - * backend keeps receiving traffic indefinitely; failing immediately means a control-plane restart - * takes every client down with it. The bound is where the deployment decides which risk it prefers, - * and it has to be stated rather than inherited. - */ -public record GrpcXdsFailurePolicy( - Duration maxStaleness, boolean failFastOnMissingResource, Duration initialFetchTimeout) { - - /** Refuses a policy without a staleness bound. */ - public GrpcXdsFailurePolicy { - if (maxStaleness == null || maxStaleness.isZero() || maxStaleness.isNegative()) { - throw new IllegalArgumentException( - "last-known-good needs a staleness bound; without one a decommissioned backend keeps " - + "receiving traffic indefinitely"); - } - if (initialFetchTimeout == null - || initialFetchTimeout.isZero() - || initialFetchTimeout.isNegative()) { - throw new IllegalArgumentException( - "a client with no snapshot yet needs a bound on how long it waits before failing"); - } - } - - /** The default: fifteen minutes of last-known-good, fail fast on a resource that vanished. */ - public static GrpcXdsFailurePolicy standard() { - return new GrpcXdsFailurePolicy(Duration.ofMinutes(15), true, Duration.ofSeconds(15)); - } - - /** What a client should do given the newest snapshot it holds. */ - public Decision decide(Optional snapshot, Instant now) { - if (snapshot == null || now == null) { - throw new IllegalArgumentException("a decision needs the snapshot Optional and a moment"); - } - if (snapshot.isEmpty()) { - return Decision.NO_SNAPSHOT_YET; - } - return snapshot.get().ageAt(now).compareTo(maxStaleness) > 0 - ? Decision.STALE_BEYOND_BOUND - : Decision.SERVE_LAST_KNOWN_GOOD; - } - - /** What the client does about a control-plane outage. */ - public enum Decision { - /** Nothing has arrived yet; wait until the initial fetch timeout, then fail. */ - NO_SNAPSHOT_YET, - /** Keep routing on the snapshot in hand. */ - SERVE_LAST_KNOWN_GOOD, - /** The snapshot is older than the bound; stop trusting it. */ - STALE_BEYOND_BOUND - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsProfile.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsProfile.java deleted file mode 100644 index 629b8eb2..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsProfile.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.grpc.advanced.xds; - -import dev.caskeleton.grpc.resilience.GrpcRetryOwner; -import java.net.URI; - -/** - * A proxyless xDS deployment's configuration. - * - *

xDS moves routing, load balancing, retries and often mTLS out of the application and into a - * control plane. The consequence this profile encodes is that the application must stop configuring - * them: retry policy defined in both places is defined twice, and which one wins depends on - * resolution order rather than on anyone's decision. - */ -public record GrpcXdsProfile( - URI target, - String bootstrapReference, - String resourceNamespace, - GrpcRetryOwner retryOwner, - boolean controlPlaneMutualTls) { - - /** The only scheme an xDS target may use. */ - public static final String XDS_SCHEME = "xds"; - - /** Refuses a profile that would leave retries or routing owned in two places. */ - public GrpcXdsProfile { - if (target == null || !XDS_SCHEME.equals(target.getScheme())) { - throw new IllegalArgumentException( - "an xDS profile needs an 'xds:///' target; got '" + target + "'"); - } - if (bootstrapReference == null || bootstrapReference.isBlank()) { - throw new IllegalArgumentException( - "xDS needs a bootstrap reference; without one the client has no control plane to ask"); - } - if (resourceNamespace == null || resourceNamespace.isBlank()) { - throw new IllegalArgumentException( - "an xDS profile names its resource namespace; a client that subscribes to everything " - + "receives another team's routing"); - } - if (retryOwner != GrpcRetryOwner.SERVICE_MESH) { - throw new IllegalArgumentException( - "xDS routing means the control plane owns retries; a retry owner of " - + retryOwner - + " would define retry policy in two places, and which wins depends on resolution " - + "order rather than on a decision"); - } - if (!controlPlaneMutualTls) { - throw new IllegalArgumentException( - "the control-plane connection carries routing and often certificates; it is authenticated " - + "in both directions or it is a channel that can be impersonated"); - } - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsResourceSnapshot.java b/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsResourceSnapshot.java deleted file mode 100644 index 59df6692..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsResourceSnapshot.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.grpc.advanced.xds; - -import java.time.Instant; -import java.util.List; - -/** - * What the control plane last said, and when. - * - *

The timestamp is what makes last-known-good usable. A snapshot with no age cannot answer - * whether the control plane has been silent for a minute or a day, and those are a transient blip - * and a serious incident. - */ -public record GrpcXdsResourceSnapshot( - String versionInfo, List resourceNames, Instant receivedAt) { - - /** Requires a version, at least one resource and a receipt time. */ - public GrpcXdsResourceSnapshot { - if (versionInfo == null || versionInfo.isBlank()) { - throw new IllegalArgumentException("an xDS snapshot carries the control plane's version"); - } - if (resourceNames == null || resourceNames.isEmpty()) { - throw new IllegalArgumentException( - "an empty resource set is not a snapshot; a control plane that returns nothing has not " - + "told the client its routing was removed"); - } - if (receivedAt == null) { - throw new IllegalArgumentException( - "a snapshot records when it arrived; without it, last-known-good cannot say how old it is"); - } - resourceNames = List.copyOf(resourceNames); - } - - /** How old this snapshot is at {@code now}. */ - public java.time.Duration ageAt(Instant now) { - if (now == null) { - throw new IllegalArgumentException("an age needs a moment"); - } - return java.time.Duration.between(receivedAt, now); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java deleted file mode 100644 index 32268e93..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package dev.caskeleton.grpc.advanced.bootstrap; - -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; - -class GrpcAdvancedModuleGuardTest { - - @Test - @DisplayName("every advanced capability is off unless a deployment names it") - void everythingIsOffByDefault() { - GrpcAdvancedFeatureFlags flags = GrpcAdvancedFeatureFlags.forDevelopment(); - - assertThat(flags.active()).isEmpty(); - for (GrpcAdvancedCapability capability : GrpcAdvancedCapability.values()) { - assertThat(GrpcAdvancedModuleGuard.available(flags, capability)).isFalse(); - } - } - - @Test - @DisplayName("each capability has its own flag, not a shared one") - void eachCapabilityHasItsOwnFlag() { - assertThat(GrpcAdvancedCapability.XDS.propertyKey()).isEqualTo("app.grpc.advanced.xds.enabled"); - assertThat(GrpcAdvancedCapability.GRPC_WEB.propertyKey()) - .isNotEqualTo(GrpcAdvancedCapability.XDS.propertyKey()); - - GrpcAdvancedFeatureFlags flags = - GrpcAdvancedFeatureFlags.forDevelopment().enable(GrpcAdvancedCapability.GRPC_WEB); - - assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.GRPC_WEB)).isTrue(); - assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.XDS)).isFalse(); - } - - @Test - @DisplayName("an unflagged capability is refused, and the message names the key to set") - void anUnflaggedCapabilityNamesItsKey() { - assertThatThrownBy( - () -> - GrpcAdvancedModuleGuard.require( - GrpcAdvancedFeatureFlags.forDevelopment(), GrpcAdvancedCapability.REACTOR)) - .isInstanceOf(GrpcAdvancedCapabilityDisabledException.class) - .hasMessageContaining("app.grpc.advanced.reactor.enabled=true"); - } - - @Test - @DisplayName("a WATCH capability cannot be enabled, however loudly it is flagged") - void aWatchCapabilityCannotStart() { - GrpcAdvancedFeatureFlags flags = - GrpcAdvancedFeatureFlags.forDevelopment().enable(GrpcAdvancedCapability.EDITION_2026); - - assertThat(GrpcAdvancedCapability.EDITION_2026.defaultGrade()) - .isEqualTo(GrpcCapabilityGrade.WATCH); - assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.EDITION_2026)) - .isFalse(); - assertThatThrownBy( - () -> GrpcAdvancedModuleGuard.require(flags, GrpcAdvancedCapability.EDITION_2026)) - .isInstanceOf(GrpcAdvancedCapabilityDisabledException.class) - .hasMessageContaining("tracked rather than implemented"); - } - - @Test - @DisplayName("an experimental capability needs a second approval in production") - void experimentalCapabilitiesNeedAProductionApproval() { - GrpcAdvancedFeatureFlags unapproved = - GrpcAdvancedFeatureFlags.forProduction(Set.of()).enable(GrpcAdvancedCapability.XDS); - GrpcAdvancedFeatureFlags approved = - GrpcAdvancedFeatureFlags.forProduction(Set.of(GrpcAdvancedCapability.XDS)) - .enable(GrpcAdvancedCapability.XDS); - - assertThat(GrpcAdvancedModuleGuard.available(unapproved, GrpcAdvancedCapability.XDS)).isFalse(); - assertThat(GrpcAdvancedModuleGuard.available(approved, GrpcAdvancedCapability.XDS)).isTrue(); - assertThatThrownBy( - () -> GrpcAdvancedModuleGuard.require(unapproved, GrpcAdvancedCapability.XDS)) - .isInstanceOf(GrpcAdvancedCapabilityDisabledException.class) - .hasMessageContaining("uncharacterised failure modes"); - } - - @Test - @DisplayName("an experimental capability runs outside production on its flag alone") - void experimentalCapabilitiesRunInDevelopment() { - GrpcAdvancedFeatureFlags flags = - GrpcAdvancedFeatureFlags.forDevelopment().enable(GrpcAdvancedCapability.HEDGING); - - assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.HEDGING)).isTrue(); - GrpcAdvancedModuleGuard.require(flags, GrpcAdvancedCapability.HEDGING); - } - - @Test - @DisplayName("only flagged and permitted capabilities appear as active") - void activeReflectsBothFlagAndGrade() { - GrpcAdvancedFeatureFlags flags = - GrpcAdvancedFeatureFlags.forProduction(Set.of()) - .enable(GrpcAdvancedCapability.GRPC_WEB) - .enable(GrpcAdvancedCapability.XDS) - .enable(GrpcAdvancedCapability.EDITION_2026); - - assertThat(flags.active()).containsExactly(GrpcAdvancedCapability.GRPC_WEB); - } - - @Test - @DisplayName("a deployment may raise a capability's grade on its own evidence") - void aDeploymentMayOverrideAGrade() { - GrpcAdvancedFeatureFlags flags = - GrpcAdvancedFeatureFlags.forProduction(Set.of()) - .enable(GrpcAdvancedCapability.HEDGING) - .withGrade(GrpcAdvancedCapability.HEDGING, GrpcCapabilityGrade.ADVANCED_STABLE); - - assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.HEDGING)).isTrue(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java deleted file mode 100644 index e5a0a2cf..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java +++ /dev/null @@ -1,205 +0,0 @@ -package dev.caskeleton.grpc.advanced.diagnostics; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedFeatureFlags; -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcChannelDiagnosticsPolicyTest { - - private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - - @Test - @DisplayName("diagnostics need both an admin network and an admin role") - void diagnosticsNeedBothGates() { - GrpcChannelDiagnosticsPolicy policy = GrpcChannelDiagnosticsPolicy.standard(); - - assertThat(policy.mayRead("admin", Set.of("ROLE_PLATFORM_ADMIN"))).isTrue(); - assertThat(policy.mayRead("public", Set.of("ROLE_PLATFORM_ADMIN"))).isFalse(); - assertThat(policy.mayRead("admin", Set.of("ROLE_USER"))).isFalse(); - assertThatThrownBy(() -> new GrpcChannelDiagnosticsPolicy(Set.of("admin"), Set.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("either gate alone is the whole surface"); - } - - @Test - @DisplayName("CSDS is registered only when xDS is actually enabled") - void csdsFollowsXds() { - GrpcAdvancedFeatureFlags diagnosticsOnly = - GrpcAdvancedFeatureFlags.forDevelopment() - .enable(GrpcAdvancedCapability.CHANNEL_DIAGNOSTICS); - GrpcAdvancedFeatureFlags withXds = - GrpcAdvancedFeatureFlags.forDevelopment() - .enable(GrpcAdvancedCapability.CHANNEL_DIAGNOSTICS) - .enable(GrpcAdvancedCapability.XDS); - - assertThat(GrpcChannelDiagnosticsPolicy.registerChannelz(diagnosticsOnly)).isTrue(); - assertThat(GrpcChannelDiagnosticsPolicy.registerCsds(diagnosticsOnly)).isFalse(); - assertThat(GrpcChannelDiagnosticsPolicy.registerCsds(withXds)).isTrue(); - assertThat( - GrpcChannelDiagnosticsPolicy.registerChannelz( - GrpcAdvancedFeatureFlags.forDevelopment())) - .isFalse(); - } - - @Test - @DisplayName("credential, certificate, metadata and payload fields are dropped outright") - void sensitiveFieldsAreDropped() { - Map raw = new LinkedHashMap<>(); - raw.put("connectivityState", "READY"); - raw.put("authorization", "Bearer abc"); - raw.put("peerCertificate", "-----BEGIN CERTIFICATE-----"); - raw.put("lastCallMetadata", "x-tenant=acme"); - raw.put("requestPayload", "{...}"); - - Map redacted = GrpcDiagnosticsRedactor.redact(raw, Set.of()); - - assertThat(redacted).containsOnlyKeys("connectivityState"); - assertThat(GrpcDiagnosticsRedactor.forbiddenField("privateKeyRef")).isTrue(); - assertThat(GrpcDiagnosticsRedactor.forbiddenField("subchannelCount")).isFalse(); - } - - @Test - @DisplayName("addresses are masked so two subchannels stay distinguishable but unresolvable") - void addressesAreMaskedRatherThanDropped() { - assertThat(GrpcDiagnosticsRedactor.maskAddress("10.4.13.201:9090")).isEqualTo("10.4.x.x"); - assertThat(GrpcDiagnosticsRedactor.maskAddress("10.9.13.201")).isEqualTo("10.9.x.x"); - - String ipv6 = GrpcDiagnosticsRedactor.maskAddress("[2001:db8::10]:9090"); - String hostname = GrpcDiagnosticsRedactor.maskAddress("payments.internal.example:443"); - assertThat(ipv6).startsWith("masked:").doesNotContain("2001", "db8"); - assertThat(hostname).startsWith("masked:").doesNotContain("payments", "internal.example"); - assertThat(ipv6).isNotEqualTo(hostname); - assertThat(GrpcDiagnosticsRedactor.maskAddress(null)).isEqualTo("unknown"); - - Map redacted = - GrpcDiagnosticsRedactor.redact( - Map.of("remoteAddress", "10.4.13.201:9090"), Set.of("remoteAddress")); - assertThat(redacted).containsEntry("remoteAddress", "10.4.x.x"); - } - - @Test - @DisplayName("a snapshot carrying an unmasked address is refused") - void anUnmaskedAddressIsRefused() { - assertThatThrownBy( - () -> - new GrpcChannelDiagnosticsSnapshot( - "documents-read", - "READY", - 3, - 100L, - 98L, - 2L, - List.of("10.4.13.201:9090"), - Map.of(), - NOW)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("every tenant's connection"); - } - - @Test - @DisplayName("a snapshot carries counters and states, and is accepted when masked") - void aMaskedSnapshotIsAccepted() { - GrpcChannelDiagnosticsSnapshot snapshot = - new GrpcChannelDiagnosticsSnapshot( - "documents-read", - "READY", - 3, - 100L, - 98L, - 2L, - List.of("10.4.x.x", "10.5.x.x"), - Map.of("documents-cluster", "v7"), - NOW); - - assertThat(snapshot.subchannelCount()).isEqualTo(3); - assertThat(snapshot.xdsResourceVersions()).containsEntry("documents-cluster", "v7"); - assertThat(snapshot.capturedAt()).isEqualTo(NOW); - } - - @Test - @DisplayName("a snapshot carrying a forbidden field name is refused") - void aForbiddenFieldNameIsRefused() { - assertThatThrownBy( - () -> - new GrpcChannelDiagnosticsSnapshot( - "documents-read", - "READY", - 1, - 1L, - 1L, - 0L, - List.of(), - Map.of("controlPlaneToken", "abc"), - NOW)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("may not appear in a diagnostics snapshot"); - } - - @Test - @DisplayName("the committed CSDS fixture is redacted into something publishable") - void theCommittedCsdsFixtureIsRedacted() { - String raw = resource("xds/control-plane-snapshot.json"); - - // The fixture deliberately contains the three shapes a snapshot must never carry, so the - // redactor is exercised against data shaped like the real thing. - assertThat(raw) - .contains("controlPlaneToken") - .contains("peerCertificate") - .contains("10.4.13.201:9090"); - - Map fields = new LinkedHashMap<>(); - fields.put("connectivityState", "READY"); - fields.put("subchannelCount", "3"); - fields.put("controlPlaneToken", "must-not-appear-in-a-snapshot"); - fields.put("peerCertificate", "-----BEGIN CERTIFICATE-----"); - fields.put("lastCallMetadata", "x-tenant=acme"); - fields.put("remoteAddress", "10.4.13.201:9090"); - - Map redacted = GrpcDiagnosticsRedactor.redact(fields, Set.of("remoteAddress")); - - assertThat(redacted).containsOnlyKeys("connectivityState", "subchannelCount", "remoteAddress"); - assertThat(redacted.get("remoteAddress")).isEqualTo("10.4.x.x"); - assertThat(String.join("|", redacted.values())).doesNotContain("must-not-appear-in-a-snapshot"); - } - - @Test - @DisplayName("a snapshot built from the fixture's resource versions is accepted") - void aSnapshotFromTheFixtureIsAccepted() { - assertThat(resource("xds/control-plane-snapshot.json")).contains("documents-cluster"); - - GrpcChannelDiagnosticsSnapshot snapshot = - new GrpcChannelDiagnosticsSnapshot( - "documents-read", - "READY", - 3, - 100L, - 98L, - 2L, - List.of("10.4.x.x", "10.4.x.x", "10.5.x.x"), - Map.of("documents-cluster", "v7", "documents-route", "v7", "documents-listener", "v6"), - NOW); - - assertThat(snapshot.xdsResourceVersions()).hasSize(3); - } - - private static String resource(String path) { - try (java.io.InputStream stream = - GrpcChannelDiagnosticsPolicyTest.class.getClassLoader().getResourceAsStream(path)) { - if (stream == null) { - throw new IllegalStateException("missing test resource " + path); - } - return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8); - } catch (java.io.IOException e) { - throw new java.io.UncheckedIOException(e); - } - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactorIdempotenceTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactorIdempotenceTest.java deleted file mode 100644 index b6e0deb9..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactorIdempotenceTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.grpc.advanced.diagnostics; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Masking an address twice gives the same answer as masking it once. - * - *

Not a style preference. {@code GrpcChannelDiagnosticsSnapshot} decides whether an address is - * masked by masking it and comparing, because a masked address carries no marker to look for — so - * the only way that question has an answer is if masking is idempotent. It was not: {@code - * 10.4.x.x} has no four numeric octets, fell through to the hash branch, and came back as {@code - * masked:}, which made a snapshot assembled from correctly masked addresses fail its own - * admission check. The property is asserted here, next to the function that has to hold it. - */ -class GrpcDiagnosticsRedactorIdempotenceTest { - - @Test - @DisplayName("masking a masked IPv4 address returns it unchanged") - void maskingAMaskedIpv4AddressIsANoOp() { - String masked = GrpcDiagnosticsRedactor.maskAddress("10.4.7.19:8443"); - - assertThat(masked).isEqualTo("10.4.x.x"); - assertThat(GrpcDiagnosticsRedactor.maskAddress(masked)).isEqualTo(masked); - } - - @Test - @DisplayName("masking a masked non-IPv4 address returns it unchanged") - void maskingAMaskedOpaqueAddressIsANoOp() { - String masked = GrpcDiagnosticsRedactor.maskAddress("unix:///var/run/grpc.sock"); - - assertThat(masked).startsWith("masked:"); - assertThat(GrpcDiagnosticsRedactor.maskAddress(masked)).isEqualTo(masked); - } - - @Test - @DisplayName("the placeholder for an absent address is its own mask") - void theUnknownPlaceholderIsStable() { - assertThat(GrpcDiagnosticsRedactor.maskAddress("")).isEqualTo("unknown"); - assertThat(GrpcDiagnosticsRedactor.maskAddress("unknown")).isEqualTo("unknown"); - } - - @Test - @DisplayName("an address that only looks masked is still masked") - void anAddressThatMerelyResemblesTheMaskIsStillMasked() { - // `x.x` is the mask's own suffix, so a value ending in it must not be waved through unless the - // whole value is a mask — otherwise "10.4.7.19 x.x" would be accepted as already redacted. - assertThat(GrpcDiagnosticsRedactor.maskAddress("10.4.7.19 x.x")).isNotEqualTo("10.4.7.19 x.x"); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java deleted file mode 100644 index 00b6f3e3..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcEdition2024PolicyTest { - - private static GrpcEditionCompatibilityReport report( - boolean wire, boolean json, Map toolchains) { - return new GrpcEditionCompatibilityReport("2024", wire, json, toolchains); - } - - @Test - @DisplayName("Edition 2024 is module-level opt-in, and nothing is opted in by default") - void editionIsOptInPerModule() { - GrpcEdition2024Policy policy = GrpcEdition2024Policy.notAdopted(); - - assertThat(policy.allowedIn("grpc-contract")).isFalse(); - assertThat( - new GrpcEdition2024Policy(Set.of("grpc-advanced"), Set.of(), false) - .allowedIn("grpc-advanced")) - .isTrue(); - } - - @Test - @DisplayName("a public service may not move onto the edition without a promotion") - void publicServicesNeedAPromotion() { - GrpcEdition2024Policy withoutPromotion = - new GrpcEdition2024Policy( - Set.of("grpc-advanced"), Set.of("caskeleton.document.v1.DocumentService"), false); - GrpcEdition2024Policy withPromotion = - new GrpcEdition2024Policy( - Set.of("grpc-advanced"), Set.of("caskeleton.document.v1.DocumentService"), true); - - assertThat(withoutPromotion.serviceMayMove("caskeleton.document.v1.DocumentService")).isFalse(); - assertThat(withPromotion.serviceMayMove("caskeleton.document.v1.DocumentService")).isTrue(); - assertThat(withoutPromotion.serviceMayMove("caskeleton.internal.v1.ScratchService")).isTrue(); - } - - @Test - @DisplayName("Java compiling alone is not cross-language evidence") - void javaAloneIsNotEvidence() { - GrpcEditionCompatibilityReport javaOnlyBroken = - report(true, true, Map.of("java", true, "go", false, "python", true)); - - assertThat(javaOnlyBroken.fullyCompatible()).isFalse(); - assertThat(javaOnlyBroken.brokenToolchains()).containsExactly("go"); - assertThatThrownBy(() -> report(true, true, Map.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Java alone is not cross-language"); - } - - @Test - @DisplayName("wire, JSON and source compatibility are compared separately") - void threeComparisonsAreSeparate() { - assertThat(report(false, true, Map.of("java", true)).incompatibilities()) - .singleElement() - .satisfies(problem -> assertThat(problem).contains("stored messages")); - assertThat(report(true, false, Map.of("java", true)).incompatibilities()) - .singleElement() - .satisfies(problem -> assertThat(problem).contains("browser clients")); - } - - @Test - @DisplayName("the Edition 2024 comparison fixture ships beside its proto3 twin") - void theComparisonFixtureShips() { - String source = resource("proto/edition2024/compatibility.proto"); - - assertThat(source) - .startsWith("edition = \"2024\";") - .contains("features.field_presence = EXPLICIT") - .contains("DOCUMENT_STATE_UNSPECIFIED = 0"); - } - - private static String resource(String path) { - try (InputStream stream = - GrpcEdition2024PolicyTest.class.getClassLoader().getResourceAsStream(path)) { - if (stream == null) { - throw new IllegalStateException("missing resource " + path); - } - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReportTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReportTest.java deleted file mode 100644 index 0f9ac3cf..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReportTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -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.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcEdition2026WatchReportTest { - - private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - - @Test - @DisplayName("the watch tracks four gates separately, because they land at different times") - void theWatchTracksFourGates() { - GrpcEdition2026WatchReport partial = - new GrpcEdition2026WatchReport( - GrpcEdition2026Status.RELEASED, - GrpcEdition2026Status.DRAFT, - GrpcEdition2026Status.UNKNOWN, - GrpcEdition2026Status.UNSUPPORTED, - NOW); - - assertThat(partial.outstanding()) - .hasSize(4) - .anySatisfy(item -> assertThat(item).contains("protoc support is DRAFT")) - .anySatisfy(item -> assertThat(item).contains("Buf support is UNKNOWN")) - .anySatisfy(item -> assertThat(item).contains("Java runtime support is UNSUPPORTED")); - assertThat(partial.readyToEvaluate()).isFalse(); - assertThat(GrpcEdition2026WatchReport.nothingKnown(NOW).outstanding()).hasSize(4); - } - - @Test - @DisplayName("a watch report is dated, so it cannot be told from a stale note") - void aWatchReportIsDated() { - assertThatThrownBy( - () -> - new GrpcEdition2026WatchReport( - GrpcEdition2026Status.SUPPORTED, - GrpcEdition2026Status.SUPPORTED, - GrpcEdition2026Status.SUPPORTED, - GrpcEdition2026Status.SUPPORTED, - null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("stale note"); - } - - @Test - @DisplayName("only SUPPORTED counts as usable") - void onlySupportedIsUsable() { - assertThat(GrpcEdition2026Status.SUPPORTED.usable()).isTrue(); - assertThat(GrpcEdition2026Status.RELEASED.usable()).isFalse(); - assertThat(GrpcEdition2026Status.DRAFT.usable()).isFalse(); - assertThat(GrpcEdition2026Status.UNKNOWN.usable()).isFalse(); - assertThat(GrpcEdition2026Status.UNSUPPORTED.usable()).isFalse(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java deleted file mode 100644 index f9068f89..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -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.policy.GrpcMethodPolicy; -import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile; -import dev.caskeleton.grpc.api.policy.WaitForReadyPolicy; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import dev.caskeleton.grpc.resilience.GrpcRetryOwner; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcHedgingEligibilityTest { - - private static final GrpcMethodName GET = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - private static final GrpcMethodName CREATE = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); - private static final GrpcMethodName WATCH = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); - private static final GrpcDeadlineProfile TWO_SECONDS = - GrpcDeadlineProfile.of(Duration.ofSeconds(2)); - - @Test - @DisplayName("only a read-only unary method may be hedged") - void onlyReadOnlyUnaryMayBeHedged() { - assertThat( - GrpcHedgingEligibility.eligible( - GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS), GrpcRetryOwner.GRPC_PLATFORM)) - .isTrue(); - assertThat( - GrpcHedgingEligibility.refusalReason( - GrpcMethodPolicy.nonIdempotentUnary(CREATE, TWO_SECONDS), - GrpcRetryOwner.GRPC_PLATFORM)) - .hasValueSatisfying( - reason -> assertThat(reason).contains("duplicates a success in progress")); - } - - @Test - @DisplayName("a keyed mutation is still refused; an idempotency key does not make hedging safe") - void aKeyedMutationIsStillRefused() { - GrpcMethodPolicy keyed = - new GrpcMethodPolicy( - CREATE, - RpcType.UNARY, - RpcIdempotencyProfile.IDEMPOTENCY_KEY_REQUIRED, - TWO_SECONDS, - WaitForReadyPolicy.DISABLED, - false, - 1024, - 1024); - - assertThat(GrpcHedgingEligibility.eligible(keyed, GrpcRetryOwner.GRPC_PLATFORM)).isFalse(); - } - - @Test - @DisplayName("a streaming method may not be hedged") - void streamingMayNotBeHedged() { - GrpcMethodPolicy streaming = - new GrpcMethodPolicy( - WATCH, - RpcType.SERVER_STREAMING, - RpcIdempotencyProfile.READ_ONLY, - TWO_SECONDS, - WaitForReadyPolicy.DISABLED, - false, - 1024, - 1024); - - assertThatThrownBy( - () -> GrpcHedgingEligibility.require(streaming, GrpcRetryOwner.GRPC_PLATFORM)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("two prefixes"); - } - - @Test - @DisplayName("a mesh-owned channel may not hedge in-process") - void aMeshOwnedChannelMayNotHedge() { - assertThat( - GrpcHedgingEligibility.eligible( - GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS), GrpcRetryOwner.SERVICE_MESH)) - .isFalse(); - assertThat( - GrpcHedgingEligibility.eligible( - GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS), GrpcRetryOwner.APPLICATION)) - .isFalse(); - } - - @Test - @DisplayName("hedging is capped at two attempts and needs a meaningful delay") - void hedgingIsCappedAndDelayed() { - assertThat( - GrpcHedgingPolicy.hedgeOnce(Duration.ofMillis(50), Duration.ofSeconds(2)).maxAttempts()) - .isEqualTo(2); - assertThatThrownBy(() -> new GrpcHedgingPolicy(3, Duration.ofMillis(50), Duration.ofSeconds(2))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("capped at 2"); - assertThatThrownBy(() -> new GrpcHedgingPolicy(2, Duration.ZERO, Duration.ofSeconds(2))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("doubles load for every call"); - assertThatThrownBy(() -> new GrpcHedgingPolicy(2, Duration.ofSeconds(3), Duration.ofSeconds(2))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never starts"); - } - - @Test - @DisplayName("the hedging budget bounds duplicate load and refuses an absurd ratio") - void theHedgingBudgetBoundsDuplicateLoad() { - // ratio 0.5 costs two tokens per hedge, so a four-token budget affords two hedges and then - // needs two completions before it can afford another. - GrpcHedgingBudget budget = GrpcHedgingBudget.of(0.5d, 4L); - - assertThat(budget.tryConsume()).isTrue(); - assertThat(budget.tryConsume()).isTrue(); - assertThat(budget.tryConsume()).isFalse(); - assertThat(budget.availableTokens()).isZero(); - - budget.recordCompletion(); - assertThat(budget.exhausted()).isTrue(); - budget.recordCompletion(); - assertThat(budget.exhausted()).isFalse(); - - assertThatThrownBy(() -> GrpcHedgingBudget.of(0.9d, 10L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("load decision rather than a latency one"); - } - - @Test - @DisplayName("a hedged result records both the saving and the duplicate load") - void aHedgedResultRecordsBothSides() { - GrpcHedgingResult hedged = new GrpcHedgingResult(2, 2, 1, 1, Duration.ofMillis(40)); - - assertThat(hedged.hedged()).isTrue(); - assertThat(hedged.duplicateBackendCalls()).isEqualTo(1); - assertThat(hedged.cancelledLoserAttempts()).isEqualTo(1); - assertThat(GrpcHedgingResult.firstAttemptWon(Duration.ofMillis(10)).hedged()).isFalse(); - assertThatThrownBy(() -> new GrpcHedgingResult(2, 3, 0, 0, Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GrpcHedgingResult(2, 1, 2, 0, Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcLoadBalancerSafetyPolicyTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcLoadBalancerSafetyPolicyTest.java deleted file mode 100644 index cf8c0349..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcLoadBalancerSafetyPolicyTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.discovery.GrpcEndpointCandidate; -import dev.caskeleton.grpc.advanced.discovery.GrpcLoadBalancerDecision; -import dev.caskeleton.grpc.advanced.discovery.GrpcLoadBalancerPicker; -import dev.caskeleton.grpc.advanced.discovery.GrpcLoadBalancerSafetyPolicy; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcLoadBalancerSafetyPolicyTest { - - @Test - @DisplayName("a picker may only choose an endpoint the resolver supplied") - void aPickerMayNotInventAnEndpoint() { - GrpcLoadBalancerSafetyPolicy policy = - new GrpcLoadBalancerSafetyPolicy(candidates -> GrpcEndpointCandidate.ready("10.9.9.9")); - - GrpcLoadBalancerDecision decision = - policy.pick(List.of(GrpcEndpointCandidate.ready("10.0.0.1"))); - - assertThat(decision.verdict()) - .isEqualTo(GrpcLoadBalancerDecision.Verdict.DETERMINISTIC_FALLBACK); - assertThat(decision.reason()).contains("can send a request anywhere"); - assertThat(decision.chosen()) - .hasValueSatisfying(endpoint -> assertThat(endpoint.address()).isEqualTo("10.0.0.1")); - } - - @Test - @DisplayName("a picker that throws degrades balancing, not availability") - void aThrowingPickerFallsBack() { - GrpcLoadBalancerSafetyPolicy policy = - new GrpcLoadBalancerSafetyPolicy( - candidates -> { - throw new IllegalStateException("picker bug"); - }); - - GrpcLoadBalancerDecision decision = - policy.pick(List.of(GrpcEndpointCandidate.ready("10.0.0.1"))); - - assertThat(decision.verdict()) - .isEqualTo(GrpcLoadBalancerDecision.Verdict.DETERMINISTIC_FALLBACK); - assertThat(decision.reason()).contains("IllegalStateException"); - } - - @Test - @DisplayName("a picker returning null falls back rather than failing the call") - void aNullPickFallsBack() { - GrpcLoadBalancerSafetyPolicy policy = new GrpcLoadBalancerSafetyPolicy(candidates -> null); - - assertThat(policy.pick(List.of(GrpcEndpointCandidate.ready("10.0.0.1"))).verdict()) - .isEqualTo(GrpcLoadBalancerDecision.Verdict.DETERMINISTIC_FALLBACK); - } - - @Test - @DisplayName("no selectable endpoint is a different verdict from a picker failure") - void noEndpointDiffersFromAPickerFailure() { - GrpcLoadBalancerSafetyPolicy policy = - new GrpcLoadBalancerSafetyPolicy(GrpcLoadBalancerPicker.roundRobin()); - - assertThat( - policy - .pick(List.of(new GrpcEndpointCandidate("10.0.0.1", false, true, 100, false))) - .verdict()) - .isEqualTo(GrpcLoadBalancerDecision.Verdict.NO_ENDPOINT_AVAILABLE); - assertThat( - policy - .pick(List.of(new GrpcEndpointCandidate("10.0.0.1", true, true, 100, true))) - .verdict()) - .isEqualTo(GrpcLoadBalancerDecision.Verdict.NO_ENDPOINT_AVAILABLE); - assertThat( - policy - .pick(List.of(new GrpcEndpointCandidate("10.0.0.1", true, true, 0, false))) - .verdict()) - .isEqualTo(GrpcLoadBalancerDecision.Verdict.NO_ENDPOINT_AVAILABLE); - } - - @Test - @DisplayName("a healthy endpoint is picked and reported as the picker's own choice") - void aHealthyEndpointIsPicked() { - GrpcLoadBalancerSafetyPolicy policy = - new GrpcLoadBalancerSafetyPolicy(GrpcLoadBalancerPicker.roundRobin()); - - assertThat( - policy - .pick( - List.of( - GrpcEndpointCandidate.ready("10.0.0.1"), - GrpcEndpointCandidate.ready("10.0.0.2"))) - .verdict()) - .isEqualTo(GrpcLoadBalancerDecision.Verdict.PICKED); - } - - @Test - @DisplayName("a picker sees endpoints only, never a request or a caller") - void aPickerSeesEndpointsOnly() { - assertThat(GrpcLoadBalancerPicker.class.getMethods()) - .filteredOn(method -> "pick".equals(method.getName())) - .singleElement() - .satisfies(method -> assertThat(method.getParameterCount()).isEqualTo(1)); - } - - @Test - @DisplayName("a candidate carries only routing-relevant state, bounded") - void aCandidateCarriesOnlyRoutingState() { - assertThat(GrpcEndpointCandidate.ready("10.0.0.1").selectable()).isTrue(); - assertThatThrownBy(() -> new GrpcEndpointCandidate("10.0.0.1", true, true, 5000, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("scale nobody can reason about"); - assertThatThrownBy(() -> new GrpcEndpointCandidate(" ", true, true, 100, false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a load-aware or weighted picker requires evidence before it ships") - void loadAwarePickersRequireEvidence() { - assertThat(GrpcLoadBalancerSafetyPolicy.requiresLoadEvidence(true, false)).isTrue(); - assertThat(GrpcLoadBalancerSafetyPolicy.requiresLoadEvidence(false, true)).isTrue(); - assertThat(GrpcLoadBalancerSafetyPolicy.requiresLoadEvidence(false, false)).isFalse(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java deleted file mode 100644 index 28da914c..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -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.grpc.advanced.discovery.GrpcCustomResolver; -import dev.caskeleton.grpc.advanced.discovery.GrpcEndpointSnapshot; -import dev.caskeleton.grpc.advanced.discovery.GrpcResolverSafetyPolicy; -import dev.caskeleton.grpc.advanced.discovery.GrpcResolverUpdate; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcResolverSafetyPolicyTest { - - @Test - @DisplayName("an empty or duplicate endpoint set is refused") - void anEmptyOrDuplicateEndpointSetIsRefused() { - assertThatThrownBy(() -> new GrpcEndpointSnapshot(1L, "documents", List.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("take the channel down with it"); - assertThatThrownBy( - () -> new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1", "10.0.0.1"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("skew a round-robin picker"); - assertThatThrownBy(() -> new GrpcEndpointSnapshot(0L, "documents", List.of("10.0.0.1"))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a stale revision is dropped rather than applied") - void aStaleRevisionIsDropped() { - List delivered = new ArrayList<>(); - try (GrpcCustomResolver resolver = new GrpcCustomResolver("documents", delivered::add)) { - assertThat( - resolver.offer( - GrpcResolverUpdate.endpointsOnly( - new GrpcEndpointSnapshot(2L, "documents", List.of("10.0.0.1"))))) - .isEmpty(); - assertThat( - resolver.offer( - GrpcResolverUpdate.endpointsOnly( - new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.9"))))) - .anySatisfy(violation -> assertThat(violation).contains("older ones")); - assertThat(delivered).hasSize(1); - assertThat(resolver.currentSnapshot()) - .hasValueSatisfying(snapshot -> assertThat(snapshot.revision()).isEqualTo(2L)); - assertThat(resolver.authority()).isEqualTo("documents"); - } - } - - @Test - @DisplayName("a resolver accepts nothing after close") - void aClosedResolverAcceptsNothing() { - List delivered = new ArrayList<>(); - GrpcCustomResolver resolver = new GrpcCustomResolver("documents", delivered::add); - resolver.close(); - - assertThat(resolver.closed()).isTrue(); - assertThat( - resolver.offer( - GrpcResolverUpdate.endpointsOnly( - new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1"))))) - .anySatisfy(violation -> assertThat(violation).contains("resolver is closed")); - assertThat(delivered).isEmpty(); - } - - @Test - @DisplayName("a resolver may not push credentials or business metadata") - void aResolverMayNotPushCredentials() { - GrpcResolverUpdate withCredential = - new GrpcResolverUpdate( - new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of(Map.of("authorization", "Bearer abc"))); - - assertThat(GrpcResolverSafetyPolicy.violations(withCredential, null)) - .anySatisfy(violation -> assertThat(violation).contains("never authentication material")); - assertThat(GrpcResolverSafetyPolicy.acceptedServiceConfig(withCredential, null)).isEmpty(); - } - - @Test - @DisplayName("a clean service config survives validation") - void aCleanServiceConfigSurvives() { - GrpcResolverUpdate clean = - new GrpcResolverUpdate( - new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of(Map.of("loadBalancingConfig", List.of(Map.of("round_robin", Map.of()))))); - - assertThat(GrpcResolverSafetyPolicy.violations(clean, null)).isEmpty(); - assertThat(GrpcResolverSafetyPolicy.acceptedServiceConfig(clean, null)).isPresent(); - } - - @Test - void aServiceConfigWithRetryThrottlingIsAccepted() { - // given - GrpcResolverUpdate throttled = - new GrpcResolverUpdate( - new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of(Map.of("retryThrottling", Map.of("maxTokens", 10, "tokenRatio", 0.1)))); - - // when - List violations = GrpcResolverSafetyPolicy.violations(throttled, null); - - // then - assertThat(violations).isEmpty(); - } - - @Test - void aServiceConfigThatTurnsOnRetriesIsRefused() { - // given - GrpcResolverUpdate retrying = - new GrpcResolverUpdate( - new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of( - Map.of( - "methodConfig", - List.of( - Map.of( - "name", List.of(Map.of("service", "documents.v1.Documents")), - "retryPolicy", Map.of("maxAttempts", 5)))))); - - // when - List violations = GrpcResolverSafetyPolicy.violations(retrying, null); - - // then - assertThat(violations).singleElement().asString().contains("retryPolicy or hedgingPolicy"); - } - - @Test - @DisplayName("an invalid authority is refused, because it decides which certificate is accepted") - void anInvalidAuthorityIsRefused() { - assertThat( - GrpcResolverSafetyPolicy.violations( - GrpcResolverUpdate.endpointsOnly( - new GrpcEndpointSnapshot(1L, "Documents Service", List.of("10.0.0.1"))), - null)) - .anySatisfy(violation -> assertThat(violation).contains("which certificate")); - } - - @Test - void aPresentServiceConfigMayNotBeEmpty() { - // when - Throwable failure = - catchThrowable( - () -> - new GrpcResolverUpdate( - new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of(Map.of()))); - - // then - assertThat(failure) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("absent and empty are different states"); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java deleted file mode 100644 index 4e899891..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.xds.GrpcXdsFailurePolicy; -import dev.caskeleton.grpc.advanced.xds.GrpcXdsProfile; -import dev.caskeleton.grpc.advanced.xds.GrpcXdsResourceSnapshot; -import dev.caskeleton.grpc.resilience.GrpcRetryOwner; -import java.net.URI; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcXdsProfileTest { - - private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - - private static GrpcXdsProfile profile(String namespace) { - return new GrpcXdsProfile( - URI.create("xds:///documents"), - "classpath:/xds/bootstrap.json", - namespace, - GrpcRetryOwner.SERVICE_MESH, - true); - } - - @Test - @DisplayName("an xDS profile requires an xds target, a namespace, mesh retries and mTLS") - void anXdsProfileRequiresItsFourConditions() { - assertThat(profile("caskeleton/documents").target().getScheme()).isEqualTo("xds"); - assertThatThrownBy( - () -> - new GrpcXdsProfile( - URI.create("dns:///documents"), - "file:/etc/grpc/bootstrap.json", - "ns", - GrpcRetryOwner.SERVICE_MESH, - true)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrpcXdsProfile( - URI.create("xds:///documents"), " ", "ns", GrpcRetryOwner.SERVICE_MESH, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("no control plane to ask"); - assertThatThrownBy( - () -> - new GrpcXdsProfile( - URI.create("xds:///documents"), - "file:/etc/grpc/bootstrap.json", - "ns", - GrpcRetryOwner.APPLICATION, - true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("two places"); - assertThatThrownBy( - () -> - new GrpcXdsProfile( - URI.create("xds:///documents"), - "file:/etc/grpc/bootstrap.json", - "ns", - GrpcRetryOwner.SERVICE_MESH, - false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("impersonated"); - } - - @Test - @DisplayName("last-known-good is bounded, and an empty resource set is not a snapshot") - void lastKnownGoodIsBounded() { - GrpcXdsFailurePolicy policy = GrpcXdsFailurePolicy.standard(); - GrpcXdsResourceSnapshot snapshot = - new GrpcXdsResourceSnapshot("v7", List.of("documents-cluster"), NOW); - - assertThat(policy.decide(Optional.of(snapshot), NOW.plusSeconds(60))) - .isEqualTo(GrpcXdsFailurePolicy.Decision.SERVE_LAST_KNOWN_GOOD); - assertThat(policy.decide(Optional.of(snapshot), NOW.plusSeconds(1000))) - .isEqualTo(GrpcXdsFailurePolicy.Decision.STALE_BEYOND_BOUND); - assertThat(policy.decide(Optional.empty(), NOW)) - .isEqualTo(GrpcXdsFailurePolicy.Decision.NO_SNAPSHOT_YET); - assertThat(snapshot.ageAt(NOW.plusSeconds(60))).isEqualTo(java.time.Duration.ofSeconds(60)); - assertThatThrownBy(() -> new GrpcXdsResourceSnapshot("v7", List.of(), NOW)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrpcXdsFailurePolicy( - java.time.Duration.ZERO, true, java.time.Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("receiving traffic indefinitely"); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTrackerTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTrackerTest.java deleted file mode 100644 index 0eda9b25..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTrackerTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.streaming.GrpcFlowControlPolicy; -import dev.caskeleton.grpc.streaming.GrpcSlowConsumerPolicy; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcBidiSequenceTrackerTest { - - @Test - @DisplayName("the two directions have independent sequences") - void directionsAreIndependent() { - GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker(); - - assertThat(tracker.nextClientSequence()).isEqualTo(1L); - assertThat(tracker.nextClientSequence()).isEqualTo(2L); - assertThat(tracker.nextServerSequence()).isEqualTo(1L); - assertThat(tracker.clientToServer().lastSequence()).isEqualTo(2L); - assertThat(tracker.serverToClient().lastSequence()).isEqualTo(1L); - } - - @Test - @DisplayName("half-closing one direction leaves the other open") - void halfClosingOneDirectionLeavesTheOtherOpen() { - GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker(); - tracker.halfCloseClient(); - - assertThat(tracker.clientToServer().ended()).isTrue(); - assertThat(tracker.serverToClient().ended()).isFalse(); - assertThat(tracker.bothEnded()).isFalse(); - assertThat(tracker.nextServerSequence()).isEqualTo(1L); - - tracker.halfCloseServer(); - assertThat(tracker.bothEnded()).isTrue(); - } - - @Test - @DisplayName("cancelling one direction leaves the other alone") - void cancellingOneDirectionLeavesTheOtherAlone() { - GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker(); - - tracker.cancelServer(); - - assertThat(tracker.serverToClient().cancelled()).isTrue(); - assertThat(tracker.clientToServer().ended()).isFalse(); - assertThat(tracker.nextClientSequence()).isEqualTo(1L); - } - - @Test - @DisplayName("a message after half-close is a protocol error, not a late arrival") - void aMessageAfterHalfCloseIsAnError() { - GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker(); - tracker.halfCloseClient(); - - assertThatThrownBy(tracker::nextClientSequence) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("protocol error"); - } - - @Test - @DisplayName("half-close and cancel are different endings") - void halfCloseAndCancelAreDifferent() { - assertThatThrownBy(() -> new GrpcBidiDirectionState(1L, true, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("different endings"); - assertThat(GrpcBidiDirectionState.open().cancel().ended()).isTrue(); - assertThat(GrpcBidiDirectionState.open().halfClose().ended()).isTrue(); - assertThatThrownBy(() -> GrpcBidiDirectionState.open().cancel().halfClose()) - .isInstanceOf(IllegalStateException.class); - } - - @Test - @DisplayName("a bidi resume carries both applied positions and requires a matching generation") - void aBidiResumeCarriesBothPositions() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - GrpcBidiSession bidi = - new GrpcBidiSession( - session, GrpcFlowControlPolicy.stable(), GrpcFlowControlPolicy.stable()); - bidi.sequences().nextClientSequence(); - bidi.sequences().nextServerSequence(); - bidi.sequences().nextServerSequence(); - - GrpcBidiResumeState state = bidi.resumeState(); - - assertThat(state.clientAppliedSequence()).isEqualTo(1L); - assertThat(state.serverAppliedSequence()).isEqualTo(2L); - assertThat(bidi.resumeFrom(session)).isPresent(); - assertThat(bidi.resumeFrom(session.resumed())).isEmpty(); - assertThat(state.resumed().sessionId().generation()).isEqualTo(2L); - } - - @Test - @DisplayName("each direction carries its own flow-control policy") - void eachDirectionHasItsOwnFlowControl() { - GrpcFlowControlPolicy inbound = - new GrpcFlowControlPolicy(8, 1024L, 4, GrpcSlowConsumerPolicy.TERMINATE); - GrpcBidiSession bidi = - new GrpcBidiSession( - GrpcClientStreamSessionId.newSession(), inbound, GrpcFlowControlPolicy.stable()); - - assertThat(bidi.inboundFlowControl().maxQueuedMessages()).isEqualTo(8); - assertThat(bidi.outboundFlowControl().maxQueuedMessages()).isEqualTo(256); - assertThat(bidi.complete()).isFalse(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicatorTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicatorTest.java deleted file mode 100644 index f797f2eb..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicatorTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -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.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcClientMessageDeduplicatorTest { - - private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - - private final GrpcClientMessageDeduplicator deduplicator = new GrpcClientMessageDeduplicator(); - - private static GrpcClientStreamMessage message( - GrpcClientStreamSessionId session, long sequence) { - return new GrpcClientStreamMessage<>(session, sequence, "payload-" + sequence); - } - - @Test - @DisplayName("a message is applied once, and a duplicate replays instead") - void aDuplicateReplaysRatherThanReapplying() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - deduplicator.beginSession(session, NOW); - GrpcClientStreamMessage first = message(session, 1L); - - assertThat(deduplicator.dispositionOf(first)) - .isEqualTo(GrpcClientMessageDeduplicator.Disposition.APPLY); - deduplicator.recordApplied(first, "outcome://applied/1", NOW); - - assertThat(deduplicator.dispositionOf(first)) - .isEqualTo(GrpcClientMessageDeduplicator.Disposition.REPLAY); - assertThat(deduplicator.replayOutcome(first)).contains("outcome://applied/1"); - } - - @Test - @DisplayName("a message ahead of the checkpoint is a gap, not an application") - void aMessageAheadOfTheCheckpointIsAGap() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - deduplicator.beginSession(session, NOW); - - assertThat(deduplicator.dispositionOf(message(session, 5L))) - .isEqualTo(GrpcClientMessageDeduplicator.Disposition.GAP); - } - - @Test - @DisplayName("a message for a session the server never opened is an error") - void anUnknownSessionIsAnError() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - - assertThatThrownBy(() -> deduplicator.dispositionOf(message(session, 1L))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("beginSession"); - } - - @Test - @DisplayName("a checkpoint records what was applied, not what was received") - void aCheckpointRecordsWhatWasApplied() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - GrpcClientStreamCheckpoint checkpoint = GrpcClientStreamCheckpoint.empty(session, NOW); - - assertThat(checkpoint.alreadyApplied(1L)).isFalse(); - assertThat(checkpoint.advancedTo(3L, NOW).alreadyApplied(3L)).isTrue(); - assertThatThrownBy(() -> checkpoint.advancedTo(3L, NOW).advancedTo(1L, NOW)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("two writers"); - } - - @Test - @DisplayName("a session the server no longer holds requires a new session, not a resume") - void aForgottenSessionRequiresANewOne() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - - GrpcClientStreamResumeDecision decision = - deduplicator.decideResume(session, "tenant-1", "tenant-1"); - - assertThat(decision.verdict()) - .isEqualTo(GrpcClientStreamResumeDecision.Verdict.NEW_SESSION_REQUIRED); - assertThat(decision.reason()).contains("nothing to tell which"); - } - - @Test - @DisplayName("a session presented by a different caller is refused") - void aSessionFromAnotherCallerIsRefused() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - deduplicator.beginSession(session, NOW); - - assertThat(deduplicator.decideResume(session, "tenant-2", "tenant-1").verdict()) - .isEqualTo(GrpcClientStreamResumeDecision.Verdict.REJECTED); - } - - @Test - @DisplayName("a tracked session resumes from its last applied message") - void aTrackedSessionResumes() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - deduplicator.beginSession(session, NOW); - deduplicator.recordApplied(message(session, 1L), null, NOW); - deduplicator.recordApplied(message(session, 2L), null, NOW); - - GrpcClientStreamResumeDecision decision = - deduplicator.decideResume(session, "tenant-1", "tenant-1"); - - assertThat(decision.verdict()).isEqualTo(GrpcClientStreamResumeDecision.Verdict.RESUME); - assertThat(decision.resumeFromSequence()).contains(2L); - assertThat(deduplicator.checkpointOf(session)) - .hasValueSatisfying(c -> assertThat(c.lastAppliedSequence()).isEqualTo(2L)); - } - - @Test - @DisplayName("a finished session is forgotten along with its replayable outcomes") - void endingASessionForgetsIt() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - deduplicator.beginSession(session, NOW); - deduplicator.recordApplied(message(session, 1L), "outcome://applied/1", NOW); - - deduplicator.endSession(session); - - assertThat(deduplicator.checkpointOf(session)).isEmpty(); - assertThat(deduplicator.replayOutcome(message(session, 1L))).isEmpty(); - } - - @Test - @DisplayName("only a RESUME decision carries a sequence") - void onlyResumeCarriesASequence() { - assertThat(GrpcClientStreamResumeDecision.resume(4L, "ok").resumeFromSequence()).contains(4L); - assertThat(GrpcClientStreamResumeDecision.newSession("gone").resumeFromSequence()).isEmpty(); - assertThat(GrpcClientStreamResumeDecision.reject("not yours").resumeFromSequence()).isEmpty(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicyTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicyTest.java deleted file mode 100644 index 4dd3a59c..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicyTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -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; - -class GrpcClientStreamPolicyTest { - - @Test - @DisplayName("a dedup key includes the generation, so a resend is not mistaken for a duplicate") - void dedupKeysIncludeTheGeneration() { - GrpcClientStreamSessionId first = GrpcClientStreamSessionId.newSession(); - GrpcClientStreamSessionId resumed = first.resumed(); - - assertThat(first.dedupKey(7L)).isNotEqualTo(resumed.dedupKey(7L)); - assertThat(resumed.sameSessionAs(first)).isTrue(); - assertThat(resumed.generation()).isEqualTo(2L); - } - - @Test - @DisplayName("a session id and a sequence are both bounded and one-based") - void identifiersAreBounded() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - - assertThat(session.generation()).isEqualTo(1L); - assertThatThrownBy(() -> session.dedupKey(0L)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GrpcClientStreamSessionId("", 1L)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GrpcClientStreamSessionId("s", 0L)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a message carries its session and a one-based client sequence") - void aMessageCarriesItsPosition() { - GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession(); - GrpcClientStreamMessage message = new GrpcClientStreamMessage<>(session, 3L, "payload"); - - assertThat(message.dedupKey()).isEqualTo(session.dedupKey(3L)); - assertThatThrownBy(() -> new GrpcClientStreamMessage<>(session, 0L, "payload")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GrpcClientStreamMessage<>(session, 1L, null)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("half-close is a state of its own, distinct from completion") - void halfCloseIsItsOwnState() { - assertThat(GrpcClientStreamState.OPEN.acceptsMessages()).isTrue(); - assertThat(GrpcClientStreamState.HALF_CLOSED.acceptsMessages()).isFalse(); - assertThat(GrpcClientStreamState.HALF_CLOSED.terminal()).isFalse(); - assertThat(GrpcClientStreamState.COMPLETED.terminal()).isTrue(); - assertThat(GrpcClientStreamState.CANCELLED.terminal()).isTrue(); - } - - @Test - @DisplayName("a whole client stream is never transparently retried") - void aClientStreamIsNeverWhollyRetried() { - assertThat(GrpcClientStreamPolicy.standard().wholeStreamRetryAllowed()).isFalse(); - } - - @Test - @DisplayName("an unbounded client stream policy is refused") - void anUnboundedClientStreamIsRefused() { - assertThatThrownBy( - () -> new GrpcClientStreamPolicy(Duration.ZERO, Duration.ofSeconds(1), 10, 10)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> new GrpcClientStreamPolicy(Duration.ofMinutes(1), Duration.ofMinutes(5), 10, 10)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never fires"); - assertThatThrownBy( - () -> new GrpcClientStreamPolicy(Duration.ofMinutes(5), Duration.ofSeconds(30), 0, 10)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the standard policy bounds duration, idle, rate and in-flight together") - void theStandardPolicyBoundsEverything() { - GrpcClientStreamPolicy standard = GrpcClientStreamPolicy.standard(); - - assertThat(standard.maxDuration()).isEqualTo(Duration.ofMinutes(10)); - assertThat(standard.idleTimeout()).isEqualTo(Duration.ofSeconds(30)); - assertThat(standard.maxMessagesPerSecond()).isPositive(); - assertThat(standard.maxInFlightMessages()).isPositive(); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandControllerTest.java b/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandControllerTest.java deleted file mode 100644 index f54a6409..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandControllerTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package dev.caskeleton.grpc.advanced.streaming; - -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.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcDemandControllerTest { - - private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - - @Test - @DisplayName("manual flow control is granted per method and needs a demand ceiling") - void manualFlowControlIsGrantedPerMethod() { - assertThatThrownBy(() -> new GrpcManualFlowControlPolicy(16, Duration.ofSeconds(30), false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("granted per method"); - assertThatThrownBy(() -> new GrpcManualFlowControlPolicy(0, Duration.ofSeconds(30), true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unbounded buffering"); - assertThatThrownBy(() -> new GrpcManualFlowControlPolicy(16, Duration.ZERO, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("no timeout of its own"); - } - - @Test - @DisplayName("demand is bounded, and requesting past the ceiling is refused") - void demandIsBounded() { - GrpcDemandController controller = - new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW); - - controller.request(4, NOW); - assertThat(controller.outstandingDemand()).isEqualTo(4); - assertThat(controller.demandCeiling()).isEqualTo(4); - assertThat(controller.decide(NOW, false).action()).isEqualTo(GrpcDemandDecision.Action.HOLD); - assertThatThrownBy(() -> controller.request(1, NOW)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("above the ceiling"); - - controller.messageReceived(NOW); - assertThat(controller.outstandingDemand()).isEqualTo(3); - assertThat(controller.decide(NOW, false).mayRequestMore()).isTrue(); - } - - @Test - @DisplayName("a request for fewer than one message is refused") - void aZeroRequestIsRefused() { - GrpcDemandController controller = - new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW); - - assertThatThrownBy(() -> controller.request(0, NOW)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("both sides waiting past the watchdog is reported as a suspected deadlock") - void aMutualWaitIsReportedAsADeadlock() { - GrpcDemandController controller = - new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW); - - assertThat(controller.decide(NOW.plusSeconds(29), true).action()) - .isEqualTo(GrpcDemandDecision.Action.REQUEST_MORE); - GrpcDemandDecision deadlocked = controller.decide(NOW.plusSeconds(30), true); - assertThat(deadlocked.action()).isEqualTo(GrpcDemandDecision.Action.DEADLOCK_SUSPECTED); - assertThat(deadlocked.reason()).contains("will never progress"); - assertThat(controller.decide(NOW.plusSeconds(30), false).mayRequestMore()).isTrue(); - } - - @Test - @DisplayName("activity postpones the watchdog") - void activityPostponesTheWatchdog() { - GrpcDemandController controller = - new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW); - - controller.messageReceived(NOW.plusSeconds(20)); - - assertThat(controller.decide(NOW.plusSeconds(40), true).action()) - .isEqualTo(GrpcDemandDecision.Action.REQUEST_MORE); - } - - @Test - @DisplayName("the controller never exposes a raw observer") - void theControllerExposesNoRawObserver() { - assertThat(GrpcDemandController.class.getMethods()) - .extracting(java.lang.reflect.Method::getReturnType) - .extracting(Class::getName) - .noneMatch(name -> name.startsWith("io.grpc.")); - } - - @Test - @DisplayName("a demand decision always explains itself and carries a non-negative demand") - void aDecisionExplainsItself() { - assertThatThrownBy(() -> new GrpcDemandDecision(GrpcDemandDecision.Action.HOLD, 1, " ")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GrpcDemandDecision(GrpcDemandDecision.Action.HOLD, -1, "why")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/resources/proto/edition2024/compatibility.proto b/src/platforms/grpc-advanced/grpc-advanced/src/test/resources/proto/edition2024/compatibility.proto deleted file mode 100644 index 0791ab30..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/resources/proto/edition2024/compatibility.proto +++ /dev/null @@ -1,28 +0,0 @@ -edition = "2024"; - -package caskeleton.grpc.edition.v1; - -option java_multiple_files = true; -option java_package = "caskeleton.grpc.edition.v1.generated"; - -// The Edition 2024 comparison fixture. -// -// It exists to be compiled beside its proto3 twin and compared: same fields, same numbers, same JSON -// names, with presence expressed by the edition's features rather than by `optional`. The lane's -// question is whether the two produce the same wire bytes and the same JSON, and answering it needs -// both files to exist. -// -// Not a Stable contract source. No public service moves onto an edition until the lane has produced -// cross-consumer compile evidence and a promotion ADR (GrpcEdition2024Policy.promotionApproved). -message DocumentSummary { - string id = 1; - string title = 2 [features.field_presence = EXPLICIT]; - int64 revision = 3; - repeated string labels = 4; -} - -enum DocumentState { - DOCUMENT_STATE_UNSPECIFIED = 0; - DOCUMENT_STATE_DRAFT = 1; - DOCUMENT_STATE_PUBLISHED = 2; -} diff --git a/src/platforms/grpc-advanced/grpc-advanced/src/test/resources/xds/control-plane-snapshot.json b/src/platforms/grpc-advanced/grpc-advanced/src/test/resources/xds/control-plane-snapshot.json deleted file mode 100644 index ab5db922..00000000 --- a/src/platforms/grpc-advanced/grpc-advanced/src/test/resources/xds/control-plane-snapshot.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "_comment": [ - "What CSDS reports for one client, as the diagnostics layer receives it before redaction.", - "The fixture deliberately contains three things a snapshot must not publish - a control-plane", - "token, a peer certificate and a raw socket address - so the redactor is tested against data", - "shaped like the real thing rather than against a string somebody invented for the assertion." - ], - "version_info": "v7", - "resources": { - "documents-cluster": "v7", - "documents-route": "v7", - "documents-listener": "v6" - }, - "connectivityState": "READY", - "subchannelCount": 3, - "sockets": [ - { "remoteAddress": "10.4.13.201:9090", "state": "READY" }, - { "remoteAddress": "10.4.19.87:9090", "state": "READY" }, - { "remoteAddress": "10.5.2.44:9090", "state": "TRANSIENT_FAILURE" } - ], - "controlPlaneToken": "must-not-appear-in-a-snapshot", - "peerCertificate": "-----BEGIN CERTIFICATE----- must-not-appear-in-a-snapshot", - "lastCallMetadata": "x-tenant=acme" -} diff --git a/src/platforms/grpc/AGENTS.md b/src/platforms/grpc/AGENTS.md deleted file mode 100644 index 2dd48896..00000000 --- a/src/platforms/grpc/AGENTS.md +++ /dev/null @@ -1,192 +0,0 @@ -# grpc — gRPC 플랫폼 family의 지역 정본 - -이 문서는 `grpc:*` family의 **지역 정본(local authority)**이다. gRPC platform은 기본 application build와 분리된 -`src/platforms/optional-build` build가 소유한다. 여기서 정하는 것은 family별 framework 규칙, 증거 등급, -Stable 범위의 경계와 application에 채택될 때 필요한 계약이다. - -루트 `AGENTS.md`와 충돌하면 루트가 이긴다. - -이 family는 Clean Architecture의 계층이 아니라 **벤더드 RPC 플랫폼**이다 — `messaging:*`와 같은 -자리에 있고 같은 이유로 있다. 자기 API(port)와 adapter와 조립 경계(starter)를 가지며, 애플리케이션은 -`adapter:inbound:grpc`를 통해 라이브러리로서 도달한다. - -설계 근거와 원본 계획 대비 deviation은 -[docs/design/2026-08-30-grpc-platform-adaptation-design.md](../../../docs/design/2026-08-30-grpc-platform-adaptation-design.md)가 SSOT다. - -## Family와 framework 규칙 - -leaf의 정확한 id는 registry에서 읽는다. - -| Family | 역할 | 허용 framework | -| --- | --- | --- | -| `grpc-core-api` | 식별자, method policy, 실행 증거, 실패 모델, deadline, request context, operation ledger port | **Java stdlib만.** io.grpc / Spring / protobuf / DB 타입 금지 | -| `grpc-contract` | `.proto` 스키마 소스(`src/main/proto`)와 protoc 생성 message. lint/breaking은 Buf(`buf.yaml`, CI job `grpc-proto-buf`) | `protobuf-java`(생성 코드 runtime)만. 규칙을 Java로 재구현하지 않는다 | -| `grpc-runtime` | policy(validation, context, status/rich error, TLS/credential, deadline/cancellation, retry, idempotency, streaming, size/compression) · server(typed service adapter SPI, interceptor 순서, Netty profile) · client(named channel, runtime generation, typed stub factory) · discovery(Static/DNS, pick_first/round_robin, Kubernetes routing) · admin(health, reflection, drain, policy snapshot) | `io.grpc:grpc-api`, `grpc-stub`. Spring·Netty 자체 금지 — Netty profile은 설정 모델이다 | -| `grpc-observability` | bounded metric/trace convention | `io.micrometer:micrometer-core`만 | -| `grpc-operation-ledger-jpa` | mutation idempotency의 durable 저장 | `jakarta.persistence`, `spring-data-jpa`. **port는 core-api에 있다** | -| `grpc-spring-boot-starter` | 조립 경계, typed properties, startup validator | Spring Boot autoconfigure. 여기서만 | -| `grpc-testkit` | in-process / 실제 Netty / fault / performance 인증 | io.grpc netty-shaded, inprocess. production leaf가 의존하지 않는다 | - -`grpc-core-api`가 io.grpc를 이름조차 부르지 않는다는 것이 이 family의 핵심 제약이다. 실행 증거와 -실패 모델은 "전송이 무엇을 했는가"를 기술하는 계약이고, 그 계약 안에 전송 타입이 들어가면 계약이 -전송의 일부가 된다. `GrpcStatusCode`가 io.grpc의 코드를 미러링하는 이유가 이것이고, 양방향 번역은 -`grpc-runtime`의 `GrpcStatusMapping`이 단독으로 소유한다. - -기본 전송 한도(메시지 1 MiB, metadata 8 KiB)는 `grpc-core-api`의 `GrpcTransportLimits` 한 곳에 있고, -server profile·named channel profile·method size profile·method policy 기본값·metadata budget이 모두 -그 상수를 쓴다. `GrpcPlatformStartupValidator`는 method의 inbound 한도가 server profile 한도보다 크면 -기동을 거부한다. - -`.proto`의 proto 조직 이름은 `caskeleton`이다(`package caskeleton.grpc.common.v1`, 생성 Java 패키지 -`caskeleton.grpc.common.v1.generated` — 손으로 쓴 `dev.caskeleton`과 겹치지 않는다). 템플릿을 재사용할 -때 바꾸는 방법은 `AGENTS.md` 「템플릿 재사용 체크리스트」에 있다. - -### 공용 다이제스트 헬퍼를 복사해 두는 이유 - -`grpc-runtime`(`GrpcRequestFingerprint`, `GrpcResumeTokenCodec`)은 SHA-256·HMAC-SHA256 계산을 자기 -안에 둔다. 템플릿의 `shared-contract` `digest/Sha256`·`HmacSha256`을 쓰지 않는 것은 의도다. 이 -family는 optional build에 있는 vendored 플랫폼이고 registry edge는 `grpc:*` 안에서만 닫힌다(위 표). -`shared-contract` edge를 주면 플랫폼이 템플릿 계약 leaf에 묶여 따로 떼어 쓸 수 없게 된다 — messaging -family가 같은 이유로 고른 배치(2026-08-14 messaging 모듈 리뷰 뒤 소유자가 정함)와 같다. 복사본을 고칠 때는 `shared-contract`의 정본과 -같은 규칙인지 함께 본다. - -## 증거 등급 — testkit이 하나의 leaf인 이유 - -원본 계획은 testkit을 core/in-process/netty/fault 4개 모듈로 쪼갠다. 목적은 "in-process 결과를 -네트워크 증거로 오해하지 않게 한다"이고, 이 저장소는 그 목적을 모듈 경계가 아니라 **strict test -lane**으로 표현한다(`ca.strict-test-lane`: lane은 아무것도 실행하지 않으면 실패하고 up-to-date -결과를 제공하지 않는다). - -`grpc-testkit`의 네 lane과 그 태그: - -| lane | 태그 | 증명하는 것 | -| --- | --- | --- | -| `grpcInProcessContractTest` | `grpc-inprocess` | adapter, interceptor 순서, status, validation, idempotency replay | -| `grpcNettyContractTest` | `grpc-netty` | 실제 소켓 위의 HTTP/2, TLS/mTLS, metadata·message hard limit, GOAWAY, drain | -| `grpcFaultTest` | `grpc-fault` | 각 증거 경계에서의 연결 손실, completion unknown, partial stream | -| `grpcPerformanceTest` | `grpc-performance` | latency percentile, saturation, drain budget | - -lane 분리만으로는 리포트가 잘못된 run을 인용하는 것을 막지 못하므로 `GrpcEvidenceGrade`가 런타임 -체크로 이를 붙든다: `CONTRACT` 등급으로 `tls`를 주장하면 예외다. - -**performance lane은 기본 `test`에서 제외된다**(leaf `build.gradle`). 공유 CI runner에서의 측정은 -release path의 flaky gate가 되고, flaky gate는 꺼진다. - -## Stable 범위 - -Stable RPC 유형은 **Unary와 Server Streaming뿐**이다. Client Streaming, Bidirectional Streaming, -hedging, xDS, custom resolver/LB, gRPC-Web, Servlet, Reactor, Kotlin은 전부 `grpc-advanced:*`이며 -capability flag 뒤에 있다. `GrpcPlatformStartupValidator`가 Stable catalog에 streaming method가 -등록되면 startup을 거부한다. - -`grpc-spring-boot-starter`는 어떤 advanced module도 참조하지 않는다. registry의 -`allowed_dependencies`와 `verifyCleanArchitectureDependencies`가 이를 build time에 강제한다. - -## Optional build에 있다는 것의 의미 - -`grpc:*`와 `grpc-advanced:*`는 기본 `ca-skeleton` settings에 include되지 않는다. 따라서 일반 -`:app-bootstrap:build`는 이 project들을 configure하지 않는다(목록은 registry의 `"build": "optional-grpc"`). 플랫폼 자체는 -`./gradlew -p platforms/optional-build ci`로 검증하고, application runtime에 실제 채택하려면 composition root가 -명시적으로 dependency를 가져오는 별도 변경이 필요하다. - -런타임 포함 여부와 qualification은 별개다. in-process·Netty·fault lane이 통과해도 실제 배포 환경의 -soak/performance baseline을 자동으로 의미하지 않는다. 지원 범위는 release gate와 support matrix가 -별도로 정의한다. - -## application이 이 family에 도달하는 경로 - -`messaging:*`가 겪은 bridge 부재(2026-08-14 messaging 모듈 리뷰)를 반복하지 않는 것이 이 family의 목표다. 계약상의 경로는 - -```text -application-owned port → adapter:inbound:grpc (typed service adapter) → :grpc:grpc-runtime SPI -``` - -이고 `GrpcServiceAdapter`가 그 SPI를 소유한다. inbound adapter가 outbound adapter·persistence에 -직접 닿지 않는 규칙은 app-bootstrap ArchUnit(`INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS`)이 -검사한다. 현재 `adapter:inbound:grpc`는 이 family에 의존하지 않는다 — registry의 -`allowed_dependencies`를 보라. 배선은 별도 결정이며, 그때 registry edge와 브리지가 함께 들어간다. -starter가 `operation-ledger-enabled=true`일 때 멱등성 판단 bean을 조립하는 것(03-11)은 이 배선이 아니다 — -starter는 서버를 만들지 않고, 그 bean을 서버에 붙이는 일은 채택하는 쪽의 몫이다(아래 「Durable operation -ledger adoption」). - -## 테스트 명령 - -focused test는 registry의 `gradle_path`에서 파생한다. - -```bash -cd src -./gradlew -p platforms/optional-build :grpc::test --console=plain -./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcInProcessContractTest --console=plain -./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcNettyContractTest --console=plain -./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcFaultTest --console=plain -./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcPerformanceTest --console=plain -``` - -## 금지 - -- `grpc-core-api`에서 io.grpc / Spring / protobuf / JPA 타입 사용. -- Stable leaf에서 `:grpc-advanced:*` 참조. -- `grpc-testkit`을 production leaf가 의존하는 것. -- in-process 결과로 transport capability를 주장하는 것 (`GrpcEvidenceGrade`가 거부한다). -- metric tag에 raw metadata·payload·actor/tenant/object/stream/idempotency 식별자를 넣는 것 - (`GrpcMetricCardinalityPolicy`가 거부한다). - - -### 채택할 때의 관측 게이트 - -`grpc-observability`가 구현한 metric 이름은 **아직 `docs/registries/metrics.yaml`에 등록하지 -않았다**. 이 optional family는 출하하는 런타임 capability가 아니기 때문이다. 채택하면서 저장소의 -`.seconds` / `.total` 단위 이름 규칙에 맞는 registry 항목과 그에 맞는 검증 게이트를 더하기 전에는 그 -이름을 저장소가 인증한 metric처럼 내세우지 않는다. - - -### durable operation 원장 채택 - -`grpc-spring-boot-starter`는 JPA 원장 어댑터를 전이 의존으로 끌어오지 않는다(2026-09-18 리뷰가 찾은 문제). durable -operation 멱등성이 필요한 배포는 `:grpc:grpc-operation-ledger-jpa`를 직접 더하고, -`GrpcOperationLedger` bean(`new JpaGrpcOperationLedger(repository)`)을 정의하고, 그 어댑터의 Flyway -위치 `db/migration/grpc`(V001 테이블, V002 보존 index, V003 claim attempt)를 넣고, 아래 flag를 켠다. -원장을 채택하지 않는 배포는 Spring Data JPA classpath 비용을 내지 않는다. - -| 키 (`app.grpc.platform.*`) | 기본값 | 하는 일 | -| --- | --- | --- | -| `operation-ledger-enabled` | `false` | `true`: starter가 배포의 `GrpcOperationLedger` bean 위에 `GrpcIdempotencyInterceptor`(bean `grpcIdempotencyInterceptor`)와 `GrpcOperationLedgerRetention`(bean `grpcOperationLedgerRetention`)을 조립하고, 원장 bean이 없으면 기동을 거절한다. `false`: 두 bean 모두 없고, `IDEMPOTENCY_KEY_REQUIRED`인 메서드가 있으면 기동을 거절한다 | -| `operation-ledger-claim-ttl` | `5m` | `IN_PROGRESS` claim의 주인이 살아 있다고 믿는 시간. 지나면 같은 요청의 재시도가 claim을 넘겨받는다(`GrpcOperationLedger.reclaimStale`). 키가 필요한 모든 메서드의 deadline보다 길지 않으면 기동에서 거절한다 | -| `operation-ledger-retention` | `24h` | 끝난(`COMMITTED`/`FAILED_TERMINAL`) 레코드를 `GrpcOperationLedgerRetention.purgeExpired`가 지울 수 있게 되기 전까지 두는 시간. `IN_PROGRESS` 행은 지우지 않는다 | - -기본값: 5분 TTL은 원장 계약 시험과 interceptor 시험이 인증한 값이다. unary deadline보다 훨씬 길고, -주인이 죽은 키가 클라이언트의 재시도 인내 안에 풀릴 만큼 짧다. 24시간 보존은 HTTP 멱등성 재생 TTL -(`app.capabilities.idempotency.replay-ttl`)과 같다. 레코드를 지운 뒤 같은 키로 하는 재시도는 새 -operation이므로, 보존 시간은 호출자의 재시도 창보다 길어야 한다. - -이 키들은 `docs/registries/env-keys.yaml`에 없다. optional 빌드는 출하하는 런타임이 아니라서 -`app.grpc.platform.*` 키는 하나도 없다. 조립 루트가 플랫폼을 채택할 때 registry에 들어간다. - -**starter가 interceptor를 조립하는 이유(선택지 (b)), (a)가 아닌 이유.** 2026-11-01 성숙도 리뷰는 -(a)를 제안했다: flag를 지우고 원장 bean이 있는지로 판단한다. 2026-11-03에 (b)를 골랐고 ADR-GRPC-004에 -적었다: flag를 남기고 flag는 말 그대로의 뜻이다 — true이면 판정 함수를 조립하고 그 TTL은 설정에서 -온다. (a)는 거짓 약속을 없앴겠지만 채택하는 쪽마다 같은 조립과 TTL 검증을 손으로 다시 만들게 -했다. (b)는 그것을 한곳에 둔다. interceptor bean에는 일부러 `@ConditionalOnMissingBean`이 없다: -바꿔 넣은 bean은 `operation-ledger-claim-ttl`을 소리 없이 무시하게 된다. 돌고 있는 operation의 -중복은 기다리라고 하지 않고 거절한다(`REJECT_IN_PROGRESS`). 기다렸다가 다시 묻는 선택지는 키가 -필요한 메서드가 그것을 필요로 할 때 키가 된다. - -**서버 배선은 여전히 채택하는 쪽의 몫이고, 따로 정할 일로 남는다.** starter는 서버를 만들지 -않으므로, 판정을 조립한다고 플랫폼이 `adapter:inbound:grpc`에 배선되지는 않는다(위 "배선은 -별도 결정"을 본다). `GrpcIdempotencyInterceptor`는 판정 함수이고 `io.grpc.ServerInterceptor`가 -아니다. 채택하는 쪽은 bean을 타입으로 주입받아 자기 `IDEMPOTENCY` 단계 interceptor -(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`)나 자기 -typed service adapter에서 부른다: 변경 전에 `decide(...)`, 변경의 트랜잭션 안에서 -`recordCommit(...)`, 끝난 실패에 `recordFailure(...)`. 두 기록 호출은 모두 `PROCEED` 판정이 실어 온 -`GrpcClaimToken`을 받는다: claim을 넘겨준 시도의 커밋은 거절되고(그 트랜잭션은 롤백된다) 그 실패는 -무시된다. 그래서 느린 주인이 claim을 가져간 시도를 덮어쓰지 못한다(ADR-GRPC-004). - -**지우기 일정은 채택하는 쪽의 몫이다.** `GrpcOperationLedgerRetention.purgeExpired(now)`는 기한이 지난 -끝난 행을 한계 있는 batch(문장 하나에 500)로 지우고, batch가 덜 차서 돌아오면 멈춘다. starter는 이것을 -예약하지 않는다: scheduler를 가지지 않고 어느 replica가 돌려야 하는지 알 수 없으며, 예약된 bean은 모든 -배포에 task scheduler를 강요하게 된다. 채택하는 쪽이 자기 scheduler에서 부른다(예: 한 시간마다). -지우기가 잠긴 행을 건너뛰므로 여러 replica에서 동시에 돌려도 안전하다. 한 번도 돌리지 않아도 안전하지만 -테이블이 끝없이 커진다. - -커밋은 변경의 트랜잭션 안에서 기록해야 하고 TTL은 키가 필요한 가장 느린 메서드보다 길어야 한다. 두 -이유는 모두 ADR-GRPC-004에 있다. diff --git a/src/platforms/grpc/CLAUDE.md b/src/platforms/grpc/CLAUDE.md deleted file mode 100644 index 43c994c2..00000000 --- a/src/platforms/grpc/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -@AGENTS.md diff --git a/src/platforms/grpc/grpc-contract/buf.yaml b/src/platforms/grpc/grpc-contract/buf.yaml deleted file mode 100644 index d81d5f19..00000000 --- a/src/platforms/grpc/grpc-contract/buf.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Buf module configuration for the Stable gRPC schema. -# -# Buf owns lint and breaking-change policy for src/main/proto; protoc (the Gradle protobuf plugin in -# build.gradle) owns compilation. CI runs both `buf lint` and `buf breaking` from this directory — -# see the `grpc-proto-buf` job in .github/workflows/ci-quality-gates.yml. -# -# cd src/platforms/grpc/grpc-contract -# buf lint -# buf breaking --against '#subdir=src/platforms/grpc/grpc-contract' -# -# No dependencies: the only imports are protoc's own well-known types (google/protobuf/*.proto). -version: v2 -modules: - - path: src/main/proto -lint: - use: - - STANDARD -breaking: - # FILE, not WIRE or WIRE_JSON. Wire compatibility alone would let a field rename or a Java package - # move through as "compatible" while every generated consumer stops compiling. - use: - - FILE diff --git a/src/platforms/grpc/grpc-contract/build.gradle b/src/platforms/grpc/grpc-contract/build.gradle deleted file mode 100644 index 8e93d9a6..00000000 --- a/src/platforms/grpc/grpc-contract/build.gradle +++ /dev/null @@ -1,47 +0,0 @@ -plugins { - id 'ca.platform-module' - alias(libs.plugins.protobuf) -} - -// The Stable schema: the `.proto` sources under src/main/proto and the Java that protoc generates -// from them. -// -// protoc, not a hand-written parser, decides whether the schema is valid, and Buf (buf.yaml next to -// this file) owns lint and breaking-change policy. Buf runs in CI — `.github/workflows/ -// ci-quality-gates.yml` job `grpc-proto-buf` — because it is a native binary and not a Maven -// artifact; this build does not re-implement its rules. Until 2026-09-28 this leaf was -// grpc-proto-contract + grpc-codegen, which did both with regular expressions (owner decision 18). -// -// Generated code lands under build/, in the package each file's `java_package` names -// (`caskeleton.*.generated`), which is disjoint from the hand-written `dev.caskeleton` root. -// Messages only: the schema declares no service yet, so there is no grpc-java stub to generate. -dependencies { - // api: every generated message extends com.google.protobuf.GeneratedMessageV3. - api libs.protobuf.java.grpc -} - -protobuf { - protoc { - artifact = libs.protoc.get().toString() - } -} - -// The plugin resolves protoc through a configuration it creates when generateProto runs, after -// resolveAndLockAll has taken its snapshot. The coordinate is an exact catalog version (libs.protoc), -// so a lock entry would restate it; locking is switched off for that tool locator only. -configurations.matching { it.name.startsWith('protobufToolsLocator_') }.configureEach { - resolutionStrategy.deactivateDependencyLocking() -} - -// Generated sources answer to protoc, not to the repository's formatter, lint or bug patterns. -spotless { - java { - target 'src/*/java/**/*.java' - } -} -tasks.named('checkstyleMain') { - exclude '**/generated/**' -} -tasks.withType(JavaCompile).configureEach { - options.errorprone.excludedPaths = '.*/build/generated/.*' -} diff --git a/src/platforms/grpc/grpc-contract/gradle.lockfile b/src/platforms/grpc/grpc-contract/gradle.lockfile deleted file mode 100644 index 206e1e19..00000000 --- a/src/platforms/grpc/grpc-contract/gradle.lockfile +++ /dev/null @@ -1,83 +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.50.0=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:3.25.8=compileClasspath,compileProtoPath,runtimeClasspath,testCompileClasspath,testCompileProtoPath,testRuntimeClasspath -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,testCompileProtoPath,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,testCompileProtoPath,testRuntimeClasspath -org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle -org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle -org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle -org.codehaus.plexus:plexus-utils:3.6.1=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=testCompileProtoPath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=testCompileProtoPath,testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath -org.junit:junit-bom:6.1.0=spotbugs -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testCompileProtoPath,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.20=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.20=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=protobuf,testProtobuf diff --git a/src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/error.proto b/src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/error.proto deleted file mode 100644 index b8324ee2..00000000 --- a/src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/error.proto +++ /dev/null @@ -1,67 +0,0 @@ -syntax = "proto3"; - -package caskeleton.grpc.common.v1; - -option java_multiple_files = true; -option java_package = "caskeleton.grpc.common.v1.generated"; -option java_outer_classname = "ErrorProto"; - -import "google/protobuf/duration.proto"; - -// The platform's allowlisted rich error details. -// -// Deliberately this repository's own messages rather than google.rpc.*: the Stable contract is that -// a client branches on a code, a reason and a typed detail — never on a message string — and owning -// the detail types is what keeps that surface reviewable. The shapes mirror google.rpc so a future -// move onto the common protos is a rename rather than a redesign. - -// Why a request was refused before it reached a use case. -message FieldViolation { - // Fully qualified field path, e.g. "document.title". - string field = 1; - // Stable machine-readable reason, e.g. "LENGTH_EXCEEDED". - string reason = 2; - // Human-readable description. Never echoes the rejected value. - optional string description = 3; -} - -// The transport validator's verdict. -message BadRequest { - repeated FieldViolation field_violations = 1; -} - -// Whether and when the caller may try again. The only channel for a retry hint. -message RetryInfo { - // Delay before the next attempt. Zero duration means "do not retry". - google.protobuf.Duration retry_delay = 1; - // Attempts already made, 1-based. - int32 attempt = 2; -} - -// A stable classification a client may branch on. -message ErrorInfo { - // Stable reason constant, e.g. "IDEMPOTENCY_KEY_REQUIRED". - string reason = 1; - // The service that produced the failure. - string domain = 2; - // Opaque execution id an operator can correlate. Never a stack trace or a driver message. - optional string execution_id = 3; -} - -// The state that made the operation impossible. -message PreconditionFailure { - message Violation { - string type = 1; - string subject = 2; - } - repeated Violation violations = 1; -} - -// What the caller may conclude about a state-changing call. -enum CompletionOutcome { - COMPLETION_OUTCOME_UNSPECIFIED = 0; - COMPLETION_OUTCOME_COMPLETED = 1; - COMPLETION_OUTCOME_REJECTED = 2; - COMPLETION_OUTCOME_COMPLETION_UNKNOWN = 3; - COMPLETION_OUTCOME_PARTIAL_STREAM = 4; -} diff --git a/src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/stream.proto b/src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/stream.proto deleted file mode 100644 index f2c5e814..00000000 --- a/src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/stream.proto +++ /dev/null @@ -1,57 +0,0 @@ -syntax = "proto3"; - -package caskeleton.grpc.common.v1; - -option java_multiple_files = true; -option java_package = "caskeleton.grpc.common.v1.generated"; -option java_outer_classname = "StreamProto"; - -// The Stable server-streaming envelope. -// -// Every Stable server stream carries these fields around its payload, because resume, gap detection -// and drain all need a position and a generation, and a stream that ships payloads alone can offer -// none of them. - -// Why a stream ended. -enum StreamTerminationReason { - STREAM_TERMINATION_REASON_UNSPECIFIED = 0; - STREAM_TERMINATION_REASON_COMPLETED = 1; - STREAM_TERMINATION_REASON_CLIENT_CANCELLED = 2; - STREAM_TERMINATION_REASON_IDLE_TIMEOUT = 3; - STREAM_TERMINATION_REASON_MAX_DURATION = 4; - STREAM_TERMINATION_REASON_SERVER_DRAIN = 5; - STREAM_TERMINATION_REASON_SLOW_CONSUMER = 6; - STREAM_TERMINATION_REASON_CREDENTIAL_EXPIRED = 7; - STREAM_TERMINATION_REASON_FULL_RESYNC_REQUIRED = 8; -} - -// What a stream message is. -enum StreamMessageKind { - STREAM_MESSAGE_KIND_UNSPECIFIED = 0; - STREAM_MESSAGE_KIND_SNAPSHOT = 1; - STREAM_MESSAGE_KIND_SNAPSHOT_COMPLETE = 2; - STREAM_MESSAGE_KIND_LIVE = 3; - STREAM_MESSAGE_KIND_HEARTBEAT = 4; - STREAM_MESSAGE_KIND_TERMINATION = 5; -} - -// The envelope every Stable server-stream message carries. -message StreamEnvelope { - // Opaque stream identity. Never used as a metric label. - string stream_id = 1; - // Monotonic within one stream generation. Restarts only on a new generation. - uint64 sequence = 2; - // The snapshot this stream is consistent with. Distinct from the resume cursor. - optional string snapshot_version = 3; - // Opaque, signed continuation handle. Absent when the stream is not resumable. - optional string resume_token = 4; - StreamMessageKind kind = 5; - // Set only on a terminal message. - optional StreamTerminationReason termination_reason = 6; -} - -// A liveness signal. Explicitly not an application acknowledgement and not an ordering guarantee. -message StreamHeartbeat { - StreamEnvelope envelope = 1; - int64 server_time_unix_millis = 2; -} diff --git a/src/platforms/grpc/grpc-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcContractGeneratedCodeTest.java b/src/platforms/grpc/grpc-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcContractGeneratedCodeTest.java deleted file mode 100644 index 0a67e169..00000000 --- a/src/platforms/grpc/grpc-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcContractGeneratedCodeTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.grpc.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import caskeleton.grpc.common.v1.generated.StreamEnvelope; -import caskeleton.grpc.common.v1.generated.StreamMessageKind; -import caskeleton.grpc.common.v1.generated.StreamTerminationReason; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcContractGeneratedCodeTest { - - @Test - @DisplayName("protoc가 생성한 stream envelope은 wire bytes로 왕복하고 명시적 presence를 유지한다") - void generatedStreamEnvelopeRoundTripsThroughWireBytesKeepingExplicitPresence() throws Exception { - // given - StreamEnvelope sent = - StreamEnvelope.newBuilder() - .setStreamId("stream-1") - .setSequence(7L) - .setKind(StreamMessageKind.STREAM_MESSAGE_KIND_TERMINATION) - .setTerminationReason(StreamTerminationReason.STREAM_TERMINATION_REASON_SERVER_DRAIN) - .build(); - - // when - StreamEnvelope received = StreamEnvelope.parseFrom(sent.toByteArray()); - - // then - assertThat(received).isEqualTo(sent); - assertThat(received.hasTerminationReason()).isTrue(); - assertThat(received.hasResumeToken()).isFalse(); - } - - @Test - @DisplayName("생성 코드의 proto 패키지와 Java 패키지는 조직 이름 caskeleton 아래에 있고 손으로 쓴 dev.caskeleton과 겹치지 않는다") - void generatedCodeLivesUnderTheCaskeletonProtoPackageAndOutsideTheHandWrittenRoot() { - // when - String protoPackage = StreamEnvelope.getDescriptor().getFile().getPackage(); - - // then - assertThat(protoPackage).isEqualTo("caskeleton.grpc.common.v1"); - assertThat(StreamEnvelope.class.getPackageName()) - .isEqualTo("caskeleton.grpc.common.v1.generated") - .doesNotStartWith("dev.caskeleton"); - } -} diff --git a/src/platforms/grpc/grpc-core-api/build.gradle b/src/platforms/grpc/grpc-core-api/build.gradle deleted file mode 100644 index 84fc01a0..00000000 --- a/src/platforms/grpc/grpc-core-api/build.gradle +++ /dev/null @@ -1,18 +0,0 @@ -plugins { - id 'ca.platform-module' - id 'java-test-fixtures' -} - -// The platform's port layer: identifiers, method policy, execution evidence, failure model, -// deadline primitives and request context. -// -// No dependencies at all, and that is the contract rather than an accident. The Stable plan's -// Global Constraints make `grpc-core-api` framework-free so "evidence and policy do not know about -// 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/platforms/grpc/grpc-core-api/gradle.lockfile b/src/platforms/grpc/grpc-core-api/gradle.lockfile deleted file mode 100644 index 042a88dd..00000000 --- a/src/platforms/grpc/grpc-core-api/gradle.lockfile +++ /dev/null @@ -1,82 +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,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,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,testFixturesAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.50.0=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.21.0=spotbugs -info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,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,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 -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,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.6.1=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,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,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,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,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,testFixturesAnnotationProcessor -org.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.20=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.20=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcClientIdentity.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcClientIdentity.java deleted file mode 100644 index 4a1ba9df..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcClientIdentity.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.grpc.api.context; - -/** - * Who is calling, as established by authentication — never as claimed by a header. - * - *

There is no factory that takes raw metadata, and that absence is the design. A tenant id read - * from an inbound header is an assertion by the caller; treating it as identity is how one tenant - * reads another's data. The only way to build this type is to name the authentication source that - * verified it. - */ -public record GrpcClientIdentity(String actorId, String tenantId, String authenticationSource) { - - /** Requires bounded values and a named verifier. */ - public GrpcClientIdentity { - requireBounded(actorId, "actor id"); - requireBounded(tenantId, "tenant id"); - requireBounded(authenticationSource, "authentication source"); - } - - private static void requireBounded(String value, String what) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(what + " must not be blank"); - } - if (value.length() > 128) { - throw new IllegalArgumentException(what + " must be at most 128 characters"); - } - for (int index = 0; index < value.length(); index++) { - if (Character.isISOControl(value.charAt(index))) { - throw new IllegalArgumentException(what + " must not contain a control character"); - } - } - } - - /** - * The only constructor a transport is allowed to reach. - * - * @param authenticationSource the verifier that established this identity — a token issuer, an - * mTLS peer certificate subject, an internal service credential. Naming it is what makes an - * audit able to answer "on what basis did we believe this". - */ - public static GrpcClientIdentity fromVerifiedAuthentication( - String actorId, String tenantId, String authenticationSource) { - return new GrpcClientIdentity(actorId, tenantId, authenticationSource); - } - - /** - * The anonymous caller, for methods that allow one. - * - *

Explicit rather than null, so "no identity" and "identity not yet resolved" are different - * states in the code that reads them. - */ - public static GrpcClientIdentity anonymous() { - return new GrpcClientIdentity("anonymous", "public", "anonymous-access-policy"); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudget.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudget.java deleted file mode 100644 index 865f061d..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudget.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.grpc.api.context; - -import dev.caskeleton.grpc.api.policy.GrpcTransportLimits; -import java.util.Map; - -/** - * Two budgets, not one: the transport's hard total, and the softer allowance for keys this - * application defines. - * - *

They are separate because they fail differently. Exceeding the hard total is a transport - * rejection that arrives as an opaque {@code RESOURCE_EXHAUSTED} from the framework with no - * indication of which header was to blame; exceeding the user-defined allowance is this platform's - * own decision, made before the call starts, with the offending key in the message. Merging them - * would mean discovering the first kind at the point where only the second kind is fixable. - */ -public record GrpcMetadataBudget(int maxTotalBytes, int maxUserDefinedBytes, int maxEntries) { - - /** Rejects an incoherent budget. */ - public GrpcMetadataBudget { - if (maxTotalBytes <= 0 || maxUserDefinedBytes <= 0 || maxEntries <= 0) { - throw new IllegalArgumentException("every metadata budget bound must be positive"); - } - if (maxUserDefinedBytes > maxTotalBytes) { - throw new IllegalArgumentException( - "user-defined allowance " - + maxUserDefinedBytes - + " cannot exceed the hard total " - + maxTotalBytes); - } - } - - /** The platform default: 8 KiB total, 4 KiB of it user-defined, at most 32 entries. */ - public static GrpcMetadataBudget standard() { - return new GrpcMetadataBudget(GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, 4096, 32); - } - - /** - * Checks a proposed metadata set before the call starts. - * - * @throws IllegalArgumentException naming the bound that was exceeded - */ - public void check(Map metadata) { - if (metadata == null) { - throw new IllegalArgumentException("metadata must not be null"); - } - if (metadata.size() > maxEntries) { - throw new IllegalArgumentException( - "metadata has " + metadata.size() + " entries; the budget allows " + maxEntries); - } - int userDefinedBytes = 0; - for (Map.Entry entry : metadata.entrySet()) { - String value = entry.getValue(); - if (value == null) { - throw new IllegalArgumentException( - "metadata key '" + entry.getKey().name() + "' has a null value"); - } - userDefinedBytes += entry.getKey().name().length() + value.length(); - } - if (userDefinedBytes > maxUserDefinedBytes) { - throw new IllegalArgumentException( - "user-defined metadata is " - + userDefinedBytes - + " bytes; the budget allows " - + maxUserDefinedBytes); - } - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataKey.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataKey.java deleted file mode 100644 index be7fe5de..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataKey.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.grpc.api.context; - -import java.util.regex.Pattern; - -/** - * A metadata key the platform is willing to carry. - * - *

The {@code grpc-} prefix is refused outright: it is reserved by the protocol, and a - * user-defined key that borrows it is a key whose meaning changes when the library is upgraded. The - * {@code -bin} suffix rule is not cosmetic either — gRPC decides base64 handling from it, so a - * binary key without the suffix is a value that arrives corrupted rather than one that arrives - * mislabelled. - */ -public record GrpcMetadataKey(String name, Kind kind) { - - /** Whether the value travels as ASCII text or as base64-encoded bytes. */ - public enum Kind { - /** Printable ASCII value. */ - ASCII, - /** Binary value; the key must end in {@code -bin}. */ - BINARY - } - - private static final Pattern CANONICAL = Pattern.compile("[a-z0-9]([a-z0-9._-]*[a-z0-9])?"); - private static final String BINARY_SUFFIX = "-bin"; - private static final String RESERVED_PREFIX = "grpc-"; - - /** Validates the name against the protocol's rules and this platform's allowlist shape. */ - public GrpcMetadataKey { - if (name == null || name.isBlank()) { - throw new IllegalArgumentException("metadata key must not be blank"); - } - if (kind == null) { - throw new IllegalArgumentException("metadata key needs a kind"); - } - if (name.length() > 64) { - throw new IllegalArgumentException("metadata key must be at most 64 characters: " + name); - } - if (!CANONICAL.matcher(name).matches()) { - throw new IllegalArgumentException( - "metadata key must be lowercase and use only [a-z0-9._-]: " + name); - } - if (name.startsWith(RESERVED_PREFIX)) { - throw new IllegalArgumentException( - "metadata key '" + name + "' uses the reserved 'grpc-' prefix"); - } - boolean binarySuffix = name.endsWith(BINARY_SUFFIX); - if (kind == Kind.BINARY && !binarySuffix) { - throw new IllegalArgumentException("binary metadata key must end in '-bin': " + name); - } - if (kind == Kind.ASCII && binarySuffix) { - throw new IllegalArgumentException("ASCII metadata key must not end in '-bin': " + name); - } - } - - /** An ASCII key. */ - public static GrpcMetadataKey ascii(String name) { - return new GrpcMetadataKey(name, Kind.ASCII); - } - - /** A binary key. */ - public static GrpcMetadataKey binary(String name) { - return new GrpcMetadataKey(name, Kind.BINARY); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcRequestContext.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcRequestContext.java deleted file mode 100644 index 4be79065..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcRequestContext.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.grpc.api.context; - -import dev.caskeleton.grpc.api.deadline.GrpcCancellationToken; -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineBudget; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * What an application use case is handed when a gRPC call reaches it. - * - *

Notice what is not here: no {@code Metadata}, no credentials, no headers map. The metadata - * that survives is the allowlisted subset, keyed by a validated {@link GrpcMetadataKey}, and the - * allowlist is supplied at construction rather than consulted from a global — so a test can state - * the allowlist it means and a second transport cannot quietly widen it. - */ -public record GrpcRequestContext( - GrpcMethodName method, - RpcType rpcType, - GrpcClientIdentity identity, - GrpcDeadlineBudget deadline, - GrpcCancellationToken cancellation, - Map metadata, - Optional traceId) { - - /** Copies the metadata map so the context cannot change after the call has started. */ - public GrpcRequestContext { - if (method == null - || rpcType == null - || identity == null - || deadline == null - || cancellation == null - || metadata == null - || traceId == null) { - throw new IllegalArgumentException("request context fields must all be present"); - } - metadata = Map.copyOf(metadata); - } - - /** - * Builds a context from inbound metadata, keeping only allowlisted keys. - * - *

Unknown keys are refused rather than dropped. Silently dropping is worse: the caller - * believes it sent a correlation id, the server never sees one, and nothing anywhere says so. - * - * @throws IllegalArgumentException when a key is outside {@code allowlist}, or the budget is - * exceeded - */ - public static GrpcRequestContext create( - GrpcMethodName method, - RpcType rpcType, - GrpcClientIdentity identity, - GrpcDeadlineBudget deadline, - GrpcCancellationToken cancellation, - Map inboundMetadata, - Set allowlist, - GrpcMetadataBudget budget, - String traceId) { - if (inboundMetadata == null || allowlist == null || budget == null) { - throw new IllegalArgumentException("metadata, allowlist and budget must all be present"); - } - Map accepted = new LinkedHashMap<>(); - for (Map.Entry entry : inboundMetadata.entrySet()) { - if (!allowlist.contains(entry.getKey())) { - throw new IllegalArgumentException( - "metadata key '" + entry.getKey().name() + "' is not on this method's allowlist"); - } - accepted.put(entry.getKey(), entry.getValue()); - } - budget.check(accepted); - return new GrpcRequestContext( - method, rpcType, identity, deadline, cancellation, accepted, Optional.ofNullable(traceId)); - } - - /** An allowlisted metadata value, if the caller sent one. */ - public Optional metadataValue(GrpcMetadataKey key) { - return Optional.ofNullable(metadata.get(key)); - } - - /** Whether the call is still worth doing work for. */ - public boolean live() { - return !cancellation.cancelled() && !deadline.expired(); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcCancellationToken.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcCancellationToken.java deleted file mode 100644 index ba422438..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcCancellationToken.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.grpc.api.deadline; - -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; - -/** - * An idempotent cancellation signal that remembers why it first fired. - * - *

"First reason wins" is the contract that makes a cancellation report usable. A call cancelled - * by its client and then, a millisecond later, by a shutdown drain has one cause and one useful - * story; a token that keeps the last write tells the second one. - */ -public final class GrpcCancellationToken { - - private final AtomicReference cancellation = new AtomicReference<>(); - - /** The reason and moment a token fired. */ - public record Cancellation(String reason, Instant at) { - /** Requires a bounded reason and a moment. */ - public Cancellation { - if (reason == null || reason.isBlank() || reason.length() > 128) { - throw new IllegalArgumentException( - "cancellation reason must be a bounded non-blank string"); - } - if (at == null) { - throw new IllegalArgumentException("cancellation needs a timestamp"); - } - } - } - - /** - * Cancels once. Later calls are accepted and ignored. - * - * @return true when this call is the one that cancelled the token - */ - public boolean cancel(String reason, Instant at) { - return cancellation.compareAndSet(null, new Cancellation(reason, at)); - } - - /** Whether the token has fired. */ - public boolean cancelled() { - return cancellation.get() != null; - } - - /** The first cancellation, if any. */ - public Optional cancellation() { - return Optional.ofNullable(cancellation.get()); - } - - /** - * Fails when the token has already fired. - * - *

Called before starting a new external side effect. The Stable plan forbids beginning one - * after cancellation, and the only way to hold that is to ask at the moment of starting. - */ - public void requireNotCancelled(String operation) { - Cancellation current = cancellation.get(); - if (current != null) { - throw new IllegalStateException( - "refusing to start '" - + operation - + "': the call was cancelled (" - + current.reason() - + ")"); - } - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudget.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudget.java deleted file mode 100644 index 02a8cbb6..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudget.java +++ /dev/null @@ -1,130 +0,0 @@ -package dev.caskeleton.grpc.api.deadline; - -import java.time.Duration; -import java.util.function.LongSupplier; - -/** - * How much time a call actually has, after the parent deadline and the method profile have both had - * their say. - * - *

The rule is "shorter of the two, minus the reserve", and it is here rather than at each call - * site because the failure mode of getting it wrong is silent: a downstream timeout longer than the - * inbound deadline never fires, and the caller sees a deadline the server has no idea it missed. - * - *

The budget is an absolute deadline on a monotonic nanosecond clock, so {@link #remaining()} - * shrinks and {@link #expired()} turns true as time passes. A request context carries one budget - * for the whole call; a budget that remembered only the duration it started with would hand every - * later dependency call the full original time. - */ -public final class GrpcDeadlineBudget { - - private final long deadlineNanos; - private final GrpcDeadlineProfile profile; - private final LongSupplier nanoClock; - - /** A budget of {@code remaining} from now on the system's monotonic clock. */ - public GrpcDeadlineBudget(Duration remaining, GrpcDeadlineProfile profile) { - this(remaining, profile, System::nanoTime); - } - - /** - * A budget of {@code remaining} from now on {@code nanoClock}. - * - * @param nanoClock a monotonic nanosecond source, {@code System::nanoTime} outside tests - */ - public GrpcDeadlineBudget( - Duration remaining, GrpcDeadlineProfile profile, LongSupplier nanoClock) { - if (remaining == null || profile == null || nanoClock == null) { - throw new IllegalArgumentException( - "a deadline budget needs a remaining time, a profile and a clock"); - } - if (remaining.isNegative()) { - throw new IllegalArgumentException("remaining time must not be negative; got " + remaining); - } - this.deadlineNanos = nanoClock.getAsLong() + remaining.toNanos(); - this.profile = profile; - this.nanoClock = nanoClock; - } - - /** - * The budget for a Stable unary entry point, which must have a positive deadline. - * - * @throws IllegalArgumentException when there is no parent deadline at all — the Stable plan - * requires every unary method to carry one, and defaulting here is how a call ends up with an - * infinite deadline nobody chose - */ - public static GrpcDeadlineBudget forEntryPoint( - Duration parentRemaining, GrpcDeadlineProfile profile) { - return forEntryPoint(parentRemaining, profile, System::nanoTime); - } - - /** {@link #forEntryPoint(Duration, GrpcDeadlineProfile)} on {@code nanoClock}. */ - public static GrpcDeadlineBudget forEntryPoint( - Duration parentRemaining, GrpcDeadlineProfile profile, LongSupplier nanoClock) { - if (profile == null) { - throw new IllegalArgumentException("a deadline budget needs a profile"); - } - if (parentRemaining == null) { - throw new IllegalArgumentException( - "a Stable unary call requires a positive deadline; none was propagated"); - } - if (parentRemaining.isZero() || parentRemaining.isNegative()) { - throw new IllegalArgumentException( - "a Stable unary call requires a positive deadline; got " + parentRemaining); - } - return new GrpcDeadlineBudget(afterReserve(parentRemaining, profile), profile, nanoClock); - } - - /** - * Derives the budget for a downstream dependency call under {@code downstream}. - * - *

Takes the shorter of what is left here now and what the downstream profile allows, then - * subtracts the downstream reserve. A dependency can never be given more time than its caller - * has. - */ - public GrpcDeadlineBudget deriveDownstream(GrpcDeadlineProfile downstream) { - if (downstream == null) { - throw new IllegalArgumentException("a downstream budget needs a profile"); - } - return new GrpcDeadlineBudget(afterReserve(remaining(), downstream), downstream, nanoClock); - } - - /** What is left now; zero once the deadline has passed. */ - public Duration remaining() { - long left = deadlineNanos - nanoClock.getAsLong(); - return left <= 0 ? Duration.ZERO : Duration.ofNanos(left); - } - - /** The profile this budget was cut from. */ - public GrpcDeadlineProfile profile() { - return profile; - } - - /** - * Whether there is enough time left to be worth starting a dependency call. - * - *

Starting one with less is not merely wasteful: it produces a deadline failure on the - * dependency that looks identical to the dependency being slow, and the resulting incident - * investigates the wrong system. - */ - public boolean canStartDependencyCall() { - Duration left = remaining(); - return !left.isZero() && left.compareTo(profile.minimumAttemptBudget()) >= 0; - } - - /** Whether any time is left at all. */ - public boolean expired() { - return remaining().isZero(); - } - - @Override - public String toString() { - return "GrpcDeadlineBudget[remaining=" + remaining() + ", profile=" + profile + "]"; - } - - private static Duration afterReserve(Duration available, GrpcDeadlineProfile profile) { - Duration bounded = available.compareTo(profile.total()) <= 0 ? available : profile.total(); - Duration afterReserve = bounded.minus(profile.safetyMargin()); - return afterReserve.isNegative() ? Duration.ZERO : afterReserve; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineExceededException.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineExceededException.java deleted file mode 100644 index c5d49af6..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineExceededException.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.grpc.api.deadline; - -import dev.caskeleton.grpc.api.error.GrpcFailureContext; -import dev.caskeleton.grpc.api.error.GrpcPlatformException; - -/** - * A deadline elapsed. - * - *

Its own type rather than a generic platform exception because callers branch on it, and - * because it is the failure most often misread: for a mutation it is a statement about time, not - * about the outcome. {@link #requiresReconciliation()} answers the question the status code cannot. - */ -public class GrpcDeadlineExceededException extends GrpcPlatformException { - - private static final long serialVersionUID = 1L; - - /** Wraps a deadline failure context. */ - public GrpcDeadlineExceededException(GrpcFailureContext context) { - super(context); - } - - /** Wraps a deadline failure context, preserving the underlying cause. */ - public GrpcDeadlineExceededException(GrpcFailureContext context, Throwable cause) { - super(context, cause); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineProfile.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineProfile.java deleted file mode 100644 index 2df50792..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineProfile.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.grpc.api.deadline; - -import java.time.Duration; - -/** - * A method's deadline shape: how long it gets, how much is held back, and the smallest slice worth - * starting a dependency call with. - * - *

The safety margin is not decoration. A downstream call handed the parent's entire remaining - * time has no room left to serialize a response or write trailers, so the caller's deadline fires - * while the answer is in flight — which produces exactly the {@code COMPLETION_UNKNOWN} the - * platform then has to reconcile. - */ -public record GrpcDeadlineProfile( - Duration total, Duration safetyMargin, Duration minimumAttemptBudget) { - - /** Rejects a profile that cannot leave usable time behind. */ - public GrpcDeadlineProfile { - if (total == null || safetyMargin == null || minimumAttemptBudget == null) { - throw new IllegalArgumentException("a deadline profile needs all three durations"); - } - if (total.isZero() || total.isNegative()) { - throw new IllegalArgumentException("total deadline must be positive; got " + total); - } - if (safetyMargin.isNegative()) { - throw new IllegalArgumentException("safety margin must not be negative"); - } - if (minimumAttemptBudget.isNegative()) { - throw new IllegalArgumentException("minimum attempt budget must not be negative"); - } - if (safetyMargin.compareTo(total) >= 0) { - throw new IllegalArgumentException( - "safety margin " + safetyMargin + " leaves no time inside total " + total); - } - if (minimumAttemptBudget.compareTo(total.minus(safetyMargin)) > 0) { - throw new IllegalArgumentException( - "minimum attempt budget " - + minimumAttemptBudget - + " exceeds the usable window " - + total.minus(safetyMargin)); - } - } - - /** - * A profile with the platform's default reserves: a tenth of the total held back for response - * serialization and trailers, and a twentieth as the smallest attempt worth starting. - */ - public static GrpcDeadlineProfile of(Duration total) { - if (total == null || total.isZero() || total.isNegative()) { - throw new IllegalArgumentException("total deadline must be positive"); - } - return new GrpcDeadlineProfile(total, total.dividedBy(10), total.dividedBy(20)); - } - - /** Total minus the reserve — the time actually available to the call. */ - public Duration usable() { - return total.minus(safetyMargin); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcCompletionOutcome.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcCompletionOutcome.java deleted file mode 100644 index 41b1029d..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcCompletionOutcome.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.grpc.api.error; - -import dev.caskeleton.grpc.core.GrpcStatusCode; -import dev.caskeleton.grpc.evidence.GrpcBusinessEvidence; -import dev.caskeleton.grpc.evidence.GrpcExecutionEvidence; -import dev.caskeleton.grpc.evidence.GrpcStreamEvidence; - -/** - * What the caller may conclude about the business operation. - * - *

Separate from the status code because the interesting case has no status of its own: a - * mutation that times out is {@code DEADLINE_EXCEEDED} on the wire and {@link #COMPLETION_UNKNOWN} - * in the business, and a caller that reads the first as the second's answer either loses a - * committed write or performs it twice. - */ -public enum GrpcCompletionOutcome { - /** The operation completed and the caller knows it. */ - COMPLETED, - /** The operation did not run; nothing changed. */ - REJECTED, - /** The operation may or may not have completed. Requires a status query or reconciliation. */ - COMPLETION_UNKNOWN, - /** A stream delivered a prefix and then ended. */ - PARTIAL_STREAM; - - /** - * Derives the outcome from a status and the evidence, for a call that changes state. - * - *

{@code DEADLINE_EXCEEDED} on a mutation defaults to {@link #COMPLETION_UNKNOWN} rather than - * to a failure, and {@code UNAVAILABLE} does the same unless the client watched the send fail. - * Those two defaults are the plan's Global Constraints, in the one place that can apply them. - */ - public static GrpcCompletionOutcome forMutation( - GrpcStatusCode statusCode, GrpcExecutionEvidence evidence) { - if (statusCode == null || evidence == null) { - throw new IllegalArgumentException("outcome derivation needs a status and evidence"); - } - if (evidence.business() == GrpcBusinessEvidence.COMMIT_CONFIRMED) { - return COMPLETED; - } - if (evidence.stream() instanceof GrpcStreamEvidence.Partial) { - return PARTIAL_STREAM; - } - if (statusCode == GrpcStatusCode.OK) { - return COMPLETED; - } - if (evidence.transport().provesNotStarted()) { - return REJECTED; - } - return switch (statusCode) { - case DEADLINE_EXCEEDED, UNAVAILABLE, CANCELLED, UNKNOWN, INTERNAL -> COMPLETION_UNKNOWN; - case INVALID_ARGUMENT, - UNAUTHENTICATED, - PERMISSION_DENIED, - NOT_FOUND, - FAILED_PRECONDITION, - OUT_OF_RANGE, - UNIMPLEMENTED, - RESOURCE_EXHAUSTED -> - REJECTED; - case OK, ALREADY_EXISTS, ABORTED, DATA_LOSS -> COMPLETION_UNKNOWN; - }; - } - - /** Whether the caller must resolve the result before acting on it. */ - public boolean requiresReconciliation() { - return this == COMPLETION_UNKNOWN; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcFailureCategory.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcFailureCategory.java deleted file mode 100644 index f6ada7a3..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcFailureCategory.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.grpc.api.error; - -import dev.caskeleton.grpc.core.GrpcStatusCode; - -/** - * The platform's stable failure taxonomy, and the canonical status each category maps to. - * - *

The mapping lives on the category rather than in a switch somewhere in the server, because the - * client needs the same table to interpret what it received. A category whose status is decided at - * the mapping site has a different answer on each side of the wire. - */ -public enum GrpcFailureCategory { - /** Malformed request; the transport validator refused it. */ - VALIDATION(GrpcStatusCode.INVALID_ARGUMENT, false), - /** No verified caller identity. */ - AUTHENTICATION(GrpcStatusCode.UNAUTHENTICATED, false), - /** A verified caller without the required permission. */ - AUTHORIZATION(GrpcStatusCode.PERMISSION_DENIED, false), - /** The addressed resource does not exist. */ - NOT_FOUND(GrpcStatusCode.NOT_FOUND, false), - /** A uniqueness or version conflict the caller can resolve. */ - CONFLICT(GrpcStatusCode.ABORTED, true), - /** The resource is in a state that forbids the operation. */ - PRECONDITION(GrpcStatusCode.FAILED_PRECONDITION, false), - /** A quota, rate limit or admission bound was hit. */ - RESOURCE_EXHAUSTED(GrpcStatusCode.RESOURCE_EXHAUSTED, true), - /** The deadline elapsed. Says nothing about whether the work completed. */ - DEADLINE(GrpcStatusCode.DEADLINE_EXCEEDED, false), - /** The caller or the platform cancelled the call. */ - CANCELLED(GrpcStatusCode.CANCELLED, false), - /** The dependency could not be reached, or refused a connection. */ - TRANSIENT_DEPENDENCY(GrpcStatusCode.UNAVAILABLE, true), - /** The dependency answered with a failure that retrying will reproduce. */ - PERMANENT_DEPENDENCY(GrpcStatusCode.INTERNAL, false), - /** The method exists in the schema but is not served. */ - UNIMPLEMENTED(GrpcStatusCode.UNIMPLEMENTED, false), - /** Stored state is inconsistent with what the contract guarantees. */ - DATA_INTEGRITY(GrpcStatusCode.DATA_LOSS, false), - /** Anything unclassified. Never carries provider detail to the client. */ - INTERNAL(GrpcStatusCode.INTERNAL, false); - - private final GrpcStatusCode statusCode; - private final boolean transientFailure; - - GrpcFailureCategory(GrpcStatusCode statusCode, boolean transientFailure) { - this.statusCode = statusCode; - this.transientFailure = transientFailure; - } - - /** The wire status this category maps to. */ - public GrpcStatusCode statusCode() { - return statusCode; - } - - /** - * Whether the same call, later, might succeed. - * - *

Necessary for a retry, never sufficient: {@code TRANSIENT_DEPENDENCY} on a non-idempotent - * mutation is still not retryable, and that decision belongs to the retry coordinator. - */ - public boolean transientFailure() { - return transientFailure; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcFailureContext.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcFailureContext.java deleted file mode 100644 index 91a30ba8..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcFailureContext.java +++ /dev/null @@ -1,99 +0,0 @@ -package dev.caskeleton.grpc.api.error; - -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.GrpcStatusCode; -import dev.caskeleton.grpc.evidence.GrpcExecutionEvidence; -import java.time.Duration; -import java.util.Optional; - -/** - * Everything the platform is willing to say about a failed attempt. - * - *

The field list is a closed allowlist rather than a convenience bag. Every field here is - * bounded and safe to log; a payload, a metadata map, a token or an idempotency key has no - * component to live in, so redaction is a property of the type rather than of whoever writes the - * log line. The provider exception survives as {@code cause} on {@link GrpcPlatformException}, - * where it reaches an operator without reaching a client. - */ -public record GrpcFailureContext( - GrpcMethodName method, - GrpcStatusCode statusCode, - GrpcFailureCategory category, - GrpcExecutionEvidence evidence, - GrpcCompletionOutcome completionOutcome, - RetryDisposition retryDisposition, - int attempt, - Duration elapsed, - Optional traceId) { - - /** - * What the platform decided about retrying this attempt, and why it is not re-derivable later. - */ - public enum RetryDisposition { - /** The attempt may be retried under the method's retry policy. */ - RETRYABLE, - /** The attempt must not be retried; repeating it risks a duplicate effect. */ - NOT_RETRYABLE, - /** Retrying is pointless: the same call will fail the same way. */ - TERMINAL, - /** The result is unknown; resolve it with a status query before deciding. */ - RESOLVE_FIRST - } - - /** Validates bounds and rejects a trace id that is not safe to log. */ - public GrpcFailureContext { - if (method == null - || statusCode == null - || category == null - || evidence == null - || completionOutcome == null - || retryDisposition == null - || elapsed == null - || traceId == null) { - throw new IllegalArgumentException("failure context fields must all be present"); - } - if (attempt < 1) { - throw new IllegalArgumentException("attempt is 1-based; got " + attempt); - } - if (elapsed.isNegative()) { - throw new IllegalArgumentException("elapsed must not be negative"); - } - if (!method.equals(evidence.method())) { - throw new IllegalArgumentException( - "failure context method '" - + method.canonical() - + "' disagrees with its evidence '" - + evidence.method().canonical() - + "'"); - } - traceId.ifPresent( - value -> { - if (value.isBlank() || value.length() > 128) { - throw new IllegalArgumentException("trace id must be a bounded non-blank identifier"); - } - }); - } - - /** - * A one-line summary safe to put in an exception message, a log line or an operator report. - * - *

Built here rather than at each call site so there is exactly one answer to "what may this - * failure say out loud". - */ - public String redactedSummary() { - return method.canonical() - + " failed with " - + statusCode - + " (" - + category - + "), outcome=" - + completionOutcome - + ", retry=" - + retryDisposition - + ", attempt=" - + attempt - + ", elapsedMs=" - + elapsed.toMillis() - + traceId.map(id -> ", trace=" + id).orElse(""); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcPlatformException.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcPlatformException.java deleted file mode 100644 index 22834504..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/error/GrpcPlatformException.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.grpc.api.error; - -/** - * The platform's failure carrier. - * - *

Its message is {@link GrpcFailureContext#redactedSummary()} and nothing else, so the string - * that ends up in a log or in a status description cannot accidentally be a driver message - * containing a SQL state, a host or a token. The original exception is kept as the cause, which is - * where an operator reads it and a client does not. - */ -public class GrpcPlatformException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient GrpcFailureContext context; - - /** Wraps a failure context. */ - public GrpcPlatformException(GrpcFailureContext context) { - this(context, null); - } - - /** Wraps a failure context, preserving the provider exception as the cause. */ - public GrpcPlatformException(GrpcFailureContext context, Throwable cause) { - super(requireContext(context).redactedSummary(), cause); - this.context = context; - } - - private static GrpcFailureContext requireContext(GrpcFailureContext context) { - if (context == null) { - throw new IllegalArgumentException("a platform exception requires a failure context"); - } - return context; - } - - /** The structured failure this exception carries. */ - public GrpcFailureContext context() { - return context; - } - - /** Whether the caller must resolve the business result before acting. */ - public boolean requiresReconciliation() { - return context.completionOutcome().requiresReconciliation(); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java deleted file mode 100644 index 269b00ed..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.grpc.api.ledger; - -/** - * Which attempt holds a claim: the fencing token a commit or a failure record must present. - * - *

A claim can change hands. A stale one is taken over after the claim TTL, and a failed one is - * re-claimed by the next retry; both make a new attempt of the same operation. The owner that lost - * the claim may still be running, and when it finishes it records its outcome. Without a token that - * record lands on the new attempt's claim: an old owner's failure turned the new attempt's claim - * {@code FAILED_TERMINAL}, a third retry re-claimed it, and two attempts ran the mutation at once - * (re-review 2026-11-03, RR-02-04). With it, the ledger records an outcome only for the attempt - * that still holds the claim. - * - *

A counter rather than the claim moment: it increases by one with every hand-over, so two - * attempts of one record never share a value, whatever the clocks of the processes that claimed it. - * The counter lives in the record: once the record is deleted ({@code release}, or the purge of a - * finished record), the next claim of the key starts again at {@link #FIRST}. Both deletions are - * therefore limited to records no live attempt can still write to — a released claim's owner is - * known to be gone, and a purged record finished longer ago than any retry (review 2026-11-03 - * RR-01-15). - * - * @param attempt one for the first claim of an operation, one more for each hand-over - */ -public record GrpcClaimToken(long attempt) { - - /** The token of the claim that created the record. */ - public static final GrpcClaimToken FIRST = new GrpcClaimToken(1); - - /** Requires a positive attempt number. */ - public GrpcClaimToken { - if (attempt < 1) { - throw new IllegalArgumentException("a claim attempt is numbered from one, was " + attempt); - } - } - - /** The token of the attempt that takes this claim over. */ - public GrpcClaimToken next() { - return new GrpcClaimToken(Math.addExact(attempt, 1)); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentity.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentity.java deleted file mode 100644 index bfd5bec2..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentity.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.grpc.api.ledger; - -import dev.caskeleton.grpc.core.GrpcMethodName; - -/** - * What makes two requests the same operation. - * - *

All three parts are load-bearing. Without the caller fingerprint, one tenant's idempotency key - * suppresses another tenant's write. Without the method, the same key reused across two operations - * makes the second one a replay of the first. Without the key, there is no operation identity at - * all. - * - *

The key is stored as a hash, never in the clear: an idempotency key is chosen by the caller - * and is frequently an order id, an invoice number or something else that identifies a person. - */ -public record GrpcOperationIdentity( - String callerFingerprint, GrpcMethodName method, String idempotencyKeyHash) { - - // Column widths of grpc_operation_ledger (V001). An identity that does not fit is refused here, - // not by the database in the middle of a claim. - private static final int MAX_CALLER_FINGERPRINT = 256; - private static final int MAX_METHOD = 256; - private static final int MAX_KEY_HASH = 80; - private static final int MAX_STORAGE_KEY = 512; - - /** Requires all three parts, with the key already hashed. */ - public GrpcOperationIdentity { - if (callerFingerprint == null || callerFingerprint.isBlank()) { - throw new IllegalArgumentException( - "an operation identity needs a caller fingerprint; without one, a key from one tenant " - + "suppresses another tenant's write"); - } - if (method == null) { - throw new IllegalArgumentException("an operation identity names its method"); - } - if (idempotencyKeyHash == null || !idempotencyKeyHash.startsWith("sha256:")) { - throw new IllegalArgumentException( - "the idempotency key is stored hashed; got '" + idempotencyKeyHash + "'"); - } - requireAtMost("caller fingerprint", callerFingerprint, MAX_CALLER_FINGERPRINT); - requireAtMost("full method name", method.canonical(), MAX_METHOD); - requireAtMost("idempotency key hash", idempotencyKeyHash, MAX_KEY_HASH); - requireAtMost( - "storage key", - callerFingerprint + "|" + method.canonical() + "|" + idempotencyKeyHash, - MAX_STORAGE_KEY); - } - - private static void requireAtMost(String what, String value, int max) { - if (value.length() > max) { - throw new IllegalArgumentException( - what - + " must be at most " - + max - + " characters to fit the ledger; got " - + value.length()); - } - } - - /** The stable storage key: the three parts joined, safe to index and safe to log. */ - public String storageKey() { - return callerFingerprint + "|" + method.canonical() + "|" + idempotencyKeyHash; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java deleted file mode 100644 index 19c239c7..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java +++ /dev/null @@ -1,156 +0,0 @@ -package dev.caskeleton.grpc.api.ledger; - -import java.time.Instant; -import java.util.Optional; - -/** - * The durable claim store behind idempotent mutations. - * - *

A port in the API leaf rather than an interface next to its JPA implementation, so the policy - * layer can require durable idempotency without depending on a database. The contract that matters - * is on {@link #claim}: it must be atomic against a unique constraint, because the two concurrent - * attempts this exists to separate arrive at the same microsecond. - */ -public interface GrpcOperationLedger { - - /** - * Claims {@code identity}, or returns the claim that already exists. - * - *

Must be a single atomic insert-or-read against a unique constraint. A read-then-insert - * implementation admits both concurrent attempts, which is the exact failure the ledger exists to - * prevent, and it does so only under the load where it matters. - * - * @return the existing record when one was already claimed, empty when this call created it — the - * caller then holds the claim as {@link GrpcClaimToken#FIRST} - */ - Optional claim( - GrpcOperationIdentity identity, String requestFingerprint, Instant now); - - /** The record for {@code identity}, if there is one. */ - Optional find(GrpcOperationIdentity identity); - - /** - * Marks a claim committed with a replayable outcome. - * - *

Called inside the business transaction wherever the datastore allows it. When the ledger and - * the mutation commit separately, there is a window in which the mutation is durable and the - * claim is not, and a retry in that window runs the mutation twice. - * - *

Only the attempt that holds the claim commits it. An attempt whose claim was taken over or - * re-claimed since is refused with an exception, so its business transaction rolls back rather - * than committing beside the attempt that now owns the operation. Of two concurrent commits of - * one claim, exactly one succeeds. - * - * @param claimToken the token of the attempt committing, from the claim it won - * @throws IllegalStateException when there is no claim, it already finished, or it is no longer - * held by {@code claimToken} - */ - void markCommitted( - GrpcOperationIdentity identity, - GrpcClaimToken claimToken, - String outcomeReference, - Instant now); - - /** - * Marks a claim terminally failed, if {@code claimToken} still holds it. - * - *

An attempt that lost its claim reports a failure the operation no longer has: another - * attempt is running it. That record is ignored rather than written over the running attempt's - * claim. - * - * @param claimToken the token of the attempt that failed, from the claim it won - * @return true when the failure was recorded; false when the claim is missing, already finished, - * or held by another attempt, in which case nothing changed - */ - boolean markFailed(GrpcOperationIdentity identity, GrpcClaimToken claimToken, 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 the new attempt's token when this call now owns the record as a fresh attempt claimed - * at {@code now}; empty otherwise - */ - Optional reclaimFailed( - GrpcOperationIdentity identity, String requestFingerprint, Instant now); - - /** - * Takes over an {@code IN_PROGRESS} claim whose owner is presumed dead, for a new attempt of the - * same request. - * - *

A claim made before {@code claimedBefore} has outlived the time its owner could still be - * working (the claim TTL), so its owner is treated as gone. Without this, a process that dies - * between claim and commit leaves its key blocked forever: every retry waits on, or is refused - * by, a claim nobody will finish. - * - *

A compare-and-set like {@link #reclaimFailed}: the record becomes a fresh {@code - * IN_PROGRESS} claim at {@code now}, and of two concurrent takeovers exactly one returns true — - * the winner's new claim moment is no longer before the cutoff, so the loser's condition fails. - * That is why {@code claimedBefore} after {@code now} is refused: the new claim would itself be - * stale and a second takeover would win too. A record in any other state, claimed at or after the - * cutoff, or made for a different request, is left untouched. - * - *

Safe only because the commit is recorded in the same transaction as the mutation (see {@link - * #markCommitted}): then a claim still {@code IN_PROGRESS} means the mutation never committed. - * When an adopter commits them separately, the abandoned attempt's outcome is unknown and a - * takeover can run the mutation twice. - * - *

The owner taken over may be slow rather than dead. Its later commit is refused and its later - * failure ignored, because it no longer holds the claim token; that is what keeps the takeover - * from becoming a second concurrent run. - * - * @return the new attempt's token when this call now owns the record as a fresh attempt claimed - * at {@code now}; empty otherwise - * @throws IllegalArgumentException when {@code claimedBefore} is after {@code now} - */ - Optional reclaimStale( - GrpcOperationIdentity identity, - String requestFingerprint, - Instant claimedBefore, - Instant now); - - /** - * Deletes up to {@code limit} finished records ({@code COMMITTED} or {@code FAILED_TERMINAL}) - * that completed before {@code completedBefore}, oldest first. - * - *

Retention, not recovery. A finished row only answers retries, so once it is older than any - * retry a caller will still send, keeping it only grows the table. Deleting it is a trade the - * deployment makes knowingly: a retry of the same key arriving after the purge is a fresh claim - * and runs the mutation again. The retention must therefore exceed the callers' retry window. - * - *

An {@code IN_PROGRESS} record is never deleted, however old. It is either running or - * abandoned, and an abandoned one is taken over by {@link #reclaimStale}, which keeps the record - * that an attempt started; deleting it would erase that. - * - *

Bounded so a backlog is drained in short transactions rather than one long delete that holds - * locks on the hottest table of the idempotency path. - * - * @return how many records were deleted, at most {@code limit} - * @throws IllegalArgumentException when {@code limit} is not positive - */ - int purgeCompletedBefore(Instant completedBefore, int limit); - - /** - * Releases a claim that will never complete, so the caller may try again: deletes the record if - * it is still {@code IN_PROGRESS} and {@code claimToken} still holds it. - * - *

Only for a claim whose owner is known to be gone. Releasing one whose owner is merely slow - * re-admits the duplicate. Fenced like every other transition (review 2026-11-03 RR-01-15): an - * attempt that lost the claim cannot delete the claim of the attempt that took it over, and a - * finished record — the answer a retry replays — is never released. - * - *

The record is gone afterwards, so the next claim of the key starts again at {@link - * GrpcClaimToken#FIRST}. An earlier attempt that lost the claim and is still running would then - * hold a token equal to the new claim's; releasing is safe only when no such attempt can still - * record an outcome — which is what "the owner is known to be gone" has to cover. - * - * @param claimToken the token of the attempt that holds the claim - * @return true when the record was deleted; false when it is missing, finished, or held by - * another attempt, in which case nothing changed - */ - boolean release(GrpcOperationIdentity identity, GrpcClaimToken claimToken); -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerRecord.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerRecord.java deleted file mode 100644 index 22f86322..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerRecord.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.grpc.api.ledger; - -import java.time.Instant; -import java.util.Optional; - -/** - * One durable operation claim, as the policy layer sees it. - * - *

The request fingerprint is what turns the ledger from a deduplicator into a correctness check. - * A caller that reuses a key for a different request has made a mistake, and returning the first - * request's answer would hide it; comparing fingerprints turns that into a {@code - * FAILED_PRECONDITION} the caller can act on. - * - *

{@code claimToken} names the attempt that holds (or last held) the claim; see {@link - * GrpcClaimToken}. - */ -public record GrpcOperationLedgerRecord( - GrpcOperationIdentity identity, - GrpcOperationLedgerState state, - String requestFingerprint, - Optional outcomeReference, - Instant claimedAt, - Optional completedAt, - GrpcClaimToken claimToken) { - - /** Requires an identity, a state, a fingerprint, a claim moment and a claim token. */ - public GrpcOperationLedgerRecord { - if (identity == null || state == null) { - throw new IllegalArgumentException("a ledger record needs an identity and a state"); - } - if (requestFingerprint == null || !requestFingerprint.startsWith("sha256:")) { - throw new IllegalArgumentException("a ledger record stores a hashed request fingerprint"); - } - if (claimedAt == null || outcomeReference == null || completedAt == null) { - throw new IllegalArgumentException("a ledger record needs its timestamps and Optionals"); - } - if (claimToken == null) { - throw new IllegalArgumentException("a ledger record names the attempt that holds it"); - } - if (state.terminal() && completedAt.isEmpty()) { - throw new IllegalArgumentException("a terminal ledger record records when it finished"); - } - if (state == GrpcOperationLedgerState.COMMITTED && outcomeReference.isEmpty()) { - throw new IllegalArgumentException( - "a COMMITTED record without an outcome reference cannot be replayed, which is the only " - + "reason to record a commit"); - } - } - - /** A fresh claim, held by the first attempt. */ - public static GrpcOperationLedgerRecord claim( - GrpcOperationIdentity identity, String requestFingerprint, Instant claimedAt) { - return claim(identity, requestFingerprint, claimedAt, GrpcClaimToken.FIRST); - } - - /** A claim in progress, held by the attempt {@code claimToken} names. */ - public static GrpcOperationLedgerRecord claim( - GrpcOperationIdentity identity, - String requestFingerprint, - Instant claimedAt, - GrpcClaimToken claimToken) { - return new GrpcOperationLedgerRecord( - identity, - GrpcOperationLedgerState.IN_PROGRESS, - requestFingerprint, - Optional.empty(), - claimedAt, - Optional.empty(), - claimToken); - } - - /** Whether {@code candidateFingerprint} is the same request this claim was made for. */ - public boolean sameRequestAs(String candidateFingerprint) { - return requestFingerprint.equals(candidateFingerprint); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java deleted file mode 100644 index 2c2cfaa0..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.grpc.api.ledger; - -/** - * Where a durable operation claim is in its life. - * - *

Three states, and the first is the one that carries the weight: {@link #IN_PROGRESS} is a - * durable record that somebody started this exact operation and has not finished. Without it, two - * concurrent attempts with the same idempotency key both find nothing and both run. - */ -public enum GrpcOperationLedgerState { - /** Claimed and running. A duplicate arriving now must wait, poll or be refused. */ - IN_PROGRESS(false), - /** Committed, with a replayable outcome. */ - COMMITTED(true), - /** - * 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; - - GrpcOperationLedgerState(boolean terminal) { - this.terminal = terminal; - } - - /** Whether the operation has finished, successfully or not. */ - public boolean terminal() { - return terminal; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicy.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicy.java deleted file mode 100644 index 3a6f8728..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicy.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.grpc.api.policy; - -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; - -/** - * Everything the platform decides per method, in one immutable value. - * - *

The contradictions are rejected here rather than at the point of use. A method declared - * non-idempotent with an explicit retry policy is not a runtime edge case to handle; it is a - * configuration that should never have been constructible, and the compact constructor is where - * that is true. - */ -public record GrpcMethodPolicy( - GrpcMethodName method, - RpcType rpcType, - RpcIdempotencyProfile idempotency, - GrpcDeadlineProfile deadline, - WaitForReadyPolicy waitForReady, - boolean explicitRetryEnabled, - int maxInboundMessageBytes, - int maxOutboundMessageBytes) { - - /** Rejects every combination the Stable plan forbids. */ - public GrpcMethodPolicy { - if (method == null || rpcType == null || idempotency == null || waitForReady == null) { - throw new IllegalArgumentException("method policy fields must all be present"); - } - if (deadline == null) { - throw new IllegalArgumentException( - "method '" - + method.canonical() - + "' has no deadline profile; every Stable method needs one"); - } - if (maxInboundMessageBytes <= 0 || maxOutboundMessageBytes <= 0) { - throw new IllegalArgumentException("message size limits must be positive"); - } - // Streaming is checked first because both rules fire for a streaming method and only one of - // them explains why: "it is STREAMING" restates the declaration, while "a retry would redeliver - // a prefix the client already saw" is the reason the declaration exists. - if (rpcType.streaming() && explicitRetryEnabled) { - throw new IllegalArgumentException( - "method '" - + method.canonical() - + "' streams; a whole-call retry would redeliver a prefix the client already saw"); - } - if (explicitRetryEnabled && !idempotency.explicitRetryAllowed()) { - throw new IllegalArgumentException( - "method '" - + method.canonical() - + "' is " - + idempotency - + " and must not carry an explicit retry policy"); - } - if (idempotency == RpcIdempotencyProfile.STREAMING && !rpcType.streaming()) { - throw new IllegalArgumentException( - "method '" + method.canonical() + "' is unary but declares the STREAMING profile"); - } - if (waitForReady.queues() && deadline.total().isZero()) { - throw new IllegalArgumentException( - "method '" - + method.canonical() - + "' enables wait-for-ready without a deadline to bound it"); - } - } - - /** A read-only unary method with the platform's default reserves. */ - public static GrpcMethodPolicy readOnlyUnary( - GrpcMethodName method, GrpcDeadlineProfile deadline) { - return new GrpcMethodPolicy( - method, - RpcType.UNARY, - RpcIdempotencyProfile.READ_ONLY, - deadline, - WaitForReadyPolicy.DISABLED, - true, - GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, - GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES); - } - - /** A state-changing unary method that refuses explicit retry. */ - public static GrpcMethodPolicy nonIdempotentUnary( - GrpcMethodName method, GrpcDeadlineProfile deadline) { - return new GrpcMethodPolicy( - method, - RpcType.UNARY, - RpcIdempotencyProfile.NON_IDEMPOTENT, - deadline, - WaitForReadyPolicy.DISABLED, - false, - GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, - GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES); - } - - /** Whether this method may be hedged. */ - public boolean hedgingAllowed() { - return rpcType == RpcType.UNARY && idempotency.hedgingAllowed(); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalog.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalog.java deleted file mode 100644 index d5e29ec3..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalog.java +++ /dev/null @@ -1,124 +0,0 @@ -package dev.caskeleton.grpc.api.policy; - -import dev.caskeleton.grpc.core.GrpcMethodName; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * The immutable method-policy lookup, built once and then only read. - * - *

Its most useful property is the one that fails a build: when a descriptor method set is - * declared, registering a policy for a method the schema does not have is an error. That catches - * the rename — the method becomes {@code CreateDocumentV2}, the policy still names {@code - * CreateDocument}, and every call to the new method silently runs with default deadline, default - * retry and no idempotency requirement. - */ -public final class GrpcMethodPolicyCatalog { - - private final Map policies; - - private GrpcMethodPolicyCatalog(Map policies) { - this.policies = Map.copyOf(policies); - } - - /** A new builder. */ - public static Builder builder() { - return new Builder(); - } - - /** The policy for {@code method}, if one is registered. */ - public Optional find(GrpcMethodName method) { - return Optional.ofNullable(policies.get(method)); - } - - /** - * The policy for {@code method}. - * - * @throws IllegalStateException when none is registered — a call with no policy has no deadline - * and no idempotency profile, and serving it would mean inventing both - */ - public GrpcMethodPolicy require(GrpcMethodName method) { - GrpcMethodPolicy policy = policies.get(method); - if (policy == null) { - throw new IllegalStateException( - "no method policy registered for '" - + method.canonical() - + "'; a Stable method without a policy has no deadline and no idempotency profile"); - } - return policy; - } - - /** Every registered method. */ - public Set methods() { - return policies.keySet(); - } - - /** How many methods carry a policy. */ - public int size() { - return policies.size(); - } - - /** Accumulates policies and validates the set as a whole at {@link #build()}. */ - public static final class Builder { - - private final Map policies = new LinkedHashMap<>(); - private final Set descriptorMethods = new LinkedHashSet<>(); - private boolean descriptorDeclared; - - private Builder() {} - - /** - * Declares the methods the compiled schema actually contains. - * - *

Optional, and the catalog is materially weaker without it: without a descriptor there is - * nothing to compare a policy's method name against. - */ - public Builder withDescriptorMethods(Set methods) { - if (methods == null || methods.isEmpty()) { - throw new IllegalArgumentException("a descriptor method set must not be empty"); - } - descriptorMethods.addAll(methods); - descriptorDeclared = true; - return this; - } - - /** - * Registers one method policy. - * - * @throws IllegalArgumentException on a duplicate registration — two policies for one method - * means the effective policy depends on registration order - */ - public Builder register(GrpcMethodPolicy policy) { - if (policy == null) { - throw new IllegalArgumentException("policy must not be null"); - } - GrpcMethodPolicy previous = policies.putIfAbsent(policy.method(), policy); - if (previous != null) { - throw new IllegalArgumentException( - "duplicate method policy for '" + policy.method().canonical() + "'"); - } - return this; - } - - /** - * Builds the catalog. - * - * @throws IllegalStateException when a registered method is absent from the declared descriptor - */ - public GrpcMethodPolicyCatalog build() { - if (descriptorDeclared) { - Set unknown = new LinkedHashSet<>(policies.keySet()); - unknown.removeAll(descriptorMethods); - if (!unknown.isEmpty()) { - throw new IllegalStateException( - "method policies reference methods the schema does not declare: " - + unknown.stream().map(GrpcMethodName::canonical).sorted().toList()); - } - } - return new GrpcMethodPolicyCatalog(policies); - } - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcTransportLimits.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcTransportLimits.java deleted file mode 100644 index c8eab4d3..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcTransportLimits.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.grpc.api.policy; - -/** - * The platform's default transport bounds, stated once. - * - *

The server profile, the named channel profiles, the per-method size profile, the method policy - * defaults and the metadata budget all start from these numbers. They used to be five copies of the - * same literals, and a copy that drifts is a method that promises a message size its server - * rejects; {@code GrpcPlatformStartupValidator} refuses that combination, and it can only do so - * cheaply when the defaults agree by construction. - */ -public final class GrpcTransportLimits { - - /** Largest message a Stable method accepts or sends by default: 1 MiB. */ - public static final int DEFAULT_MAX_MESSAGE_BYTES = 1024 * 1024; - - /** Hard total for one call's metadata: 8 KiB. */ - public static final int DEFAULT_MAX_METADATA_BYTES = 8192; - - private GrpcTransportLimits() {} -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/RpcIdempotencyProfile.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/RpcIdempotencyProfile.java deleted file mode 100644 index 814c49a8..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/RpcIdempotencyProfile.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.grpc.api.policy; - -/** - * How safe a method is to run more than once — the property every retry decision starts from. - * - *

Idempotency is a property of the operation, not of the failure, and keeping it on the method - * policy rather than deriving it from a status is what stops "UNAVAILABLE means retry" from being - * applied to a transfer. - */ -public enum RpcIdempotencyProfile { - /** Reads nothing changes. Retryable and the only profile eligible for hedging. */ - READ_ONLY(true, true, false), - /** Repeating the write reaches the same end state — a set-to-value, a delete-by-id. */ - NATURALLY_IDEMPOTENT(true, false, false), - /** Safe to repeat only with a caller-supplied key and a durable ledger behind it. */ - IDEMPOTENCY_KEY_REQUIRED(true, false, true), - /** Safe to repeat only when a precondition — a version, an ETag — is carried and checked. */ - CONDITIONALLY_IDEMPOTENT(true, false, false), - /** Repeating it does it twice. No explicit retry, no hedging, ever. */ - NON_IDEMPOTENT(false, false, false), - /** A stream. Whole-call retry is meaningless once a prefix has been delivered. */ - STREAMING(false, false, false); - - private final boolean explicitRetryAllowed; - private final boolean hedgingAllowed; - private final boolean idempotencyKeyRequired; - - RpcIdempotencyProfile( - boolean explicitRetryAllowed, boolean hedgingAllowed, boolean idempotencyKeyRequired) { - this.explicitRetryAllowed = explicitRetryAllowed; - this.hedgingAllowed = hedgingAllowed; - this.idempotencyKeyRequired = idempotencyKeyRequired; - } - - /** Whether an explicit retry policy may be attached to a method with this profile. */ - public boolean explicitRetryAllowed() { - return explicitRetryAllowed; - } - - /** Whether duplicate in-flight attempts may be issued. Only reads qualify. */ - public boolean hedgingAllowed() { - return hedgingAllowed; - } - - /** Whether the caller must supply an idempotency key for the call to be accepted. */ - public boolean idempotencyKeyRequired() { - return idempotencyKeyRequired; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/WaitForReadyPolicy.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/WaitForReadyPolicy.java deleted file mode 100644 index 65f31915..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/WaitForReadyPolicy.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.grpc.api.policy; - -/** - * Whether a call queues while the channel is disconnected, instead of failing fast. - * - *

Default off. Wait-for-ready turns a fast {@code UNAVAILABLE} into a wait that ends at the - * deadline, which is the right trade for a batch worker and the wrong one for a request a person is - * watching — the user gets the whole deadline as latency and then an error anyway. - */ -public enum WaitForReadyPolicy { - /** Fail fast when the channel is not ready. The default for every method. */ - DISABLED, - /** A worker or batch path may queue inside its deadline and queue budget. */ - WORKER_OPT_IN, - /** A user-synchronous path that has been explicitly reviewed and approved to queue. */ - APPROVED_SYNCHRONOUS; - - /** Whether calls under this policy queue rather than fail fast. */ - public boolean queues() { - return this != DISABLED; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcChannelProfileName.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcChannelProfileName.java deleted file mode 100644 index 10d63f7e..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcChannelProfileName.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.grpc.core; - -import java.util.regex.Pattern; - -/** - * The logical name of a client channel profile — {@code document-service-read}, not a host. - * - *

A channel is named for the traffic it carries rather than for where it points, because the - * same backend reached with a long-stream SLO and with a short-unary SLO is two channels. Naming - * them both after the service is what makes that distinction disappear. - */ -public record GrpcChannelProfileName(String value) { - - private static final Pattern CANONICAL = Pattern.compile("[a-z][a-z0-9]*(-[a-z0-9]+)*"); - - /** Validates the canonical lower-kebab form. */ - public GrpcChannelProfileName { - GrpcIdentifiers.requireBounded(value, "channel profile name"); - if (!CANONICAL.matcher(value).matches()) { - throw new IllegalArgumentException( - "channel profile name must be lower-kebab-case; got '" + value + "'"); - } - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcIdentifiers.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcIdentifiers.java deleted file mode 100644 index 2fe99149..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcIdentifiers.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.grpc.core; - -/** - * Shared validation for the platform's bounded identifiers. - * - *

Package-private machinery rather than a public helper: the rule that an identifier rejects - * blanks and control characters belongs to the identifiers, and a public utility would invite - * callers to validate a string and then carry it as a {@code String} anyway — which is the thing - * the identifier types exist to stop. - */ -final class GrpcIdentifiers { - - private GrpcIdentifiers() {} - - /** Longest identifier this platform accepts, in characters. */ - static final int MAX_LENGTH = 256; - - /** - * Returns {@code value} when it is a well-formed identifier segment. - * - * @throws IllegalArgumentException when it is null, blank, over-long, or carries a control - * character — including the ones that would forge a log line or a metadata frame - */ - static String requireBounded(String value, String what) { - if (value == null) { - throw new IllegalArgumentException(what + " must not be null"); - } - if (value.isBlank()) { - throw new IllegalArgumentException(what + " must not be blank"); - } - if (value.length() > MAX_LENGTH) { - throw new IllegalArgumentException( - what + " must be at most " + MAX_LENGTH + " characters; got " + value.length()); - } - for (int index = 0; index < value.length(); index++) { - char character = value.charAt(index); - if (Character.isISOControl(character)) { - throw new IllegalArgumentException( - what + " must not contain a control character at index " + index); - } - if (Character.isWhitespace(character)) { - throw new IllegalArgumentException(what + " must not contain whitespace at index " + index); - } - } - return value; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcMethodName.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcMethodName.java deleted file mode 100644 index 26528fb0..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcMethodName.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.grpc.core; - -import java.util.regex.Pattern; - -/** - * The canonical full method name, {@code package.Service/Method}. - * - *

This is the identity every other contract keys on: the policy catalog, the descriptor, the - * operation ledger, the retry decision and the observation convention all have to agree on one - * spelling of a method, and this type is that spelling. It is deliberately the same string gRPC - * itself uses for a full method name, so a descriptor and a catalog cannot disagree about which - * method a policy covers. - */ -public record GrpcMethodName(GrpcServiceName service, String method) { - - private static final Pattern METHOD = Pattern.compile("[A-Z][A-Za-z0-9_]*"); - - /** Validates the method half; the service half validates itself. */ - public GrpcMethodName { - if (service == null) { - throw new IllegalArgumentException("method name requires a service"); - } - GrpcIdentifiers.requireBounded(method, "method name"); - if (!METHOD.matcher(method).matches()) { - throw new IllegalArgumentException( - "method must be an UpperCamelCase proto method name; got '" + method + "'"); - } - // The same bound parse() applies to the whole name, so both ways of making a method name - // accept exactly the same set of names. - int fullLength = service.value().length() + 1 + method.length(); - if (fullLength > GrpcIdentifiers.MAX_LENGTH) { - throw new IllegalArgumentException( - "full method name must be at most " - + GrpcIdentifiers.MAX_LENGTH - + " characters; got " - + fullLength); - } - } - - /** - * Parses {@code package.Service/Method}. - * - * @throws IllegalArgumentException when the canonical separator is missing or repeated — a name - * with two slashes is not a method name with a slash in it, it is a different string - */ - public static GrpcMethodName parse(String canonical) { - GrpcIdentifiers.requireBounded(canonical, "full method name"); - int separator = canonical.indexOf('/'); - if (separator < 0) { - throw new IllegalArgumentException( - "full method name must be 'package.Service/Method'; got '" + canonical + "'"); - } - if (canonical.indexOf('/', separator + 1) >= 0) { - throw new IllegalArgumentException( - "full method name must contain exactly one '/'; got '" + canonical + "'"); - } - return new GrpcMethodName( - new GrpcServiceName(canonical.substring(0, separator)), canonical.substring(separator + 1)); - } - - /** The canonical {@code package.Service/Method} form. */ - public String canonical() { - return service.value() + "/" + method; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcServiceName.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcServiceName.java deleted file mode 100644 index 6a44d227..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcServiceName.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.grpc.core; - -import java.util.regex.Pattern; - -/** - * A fully qualified Protobuf service name — {@code package.subpackage.ServiceName}. - * - *

Bounded on purpose. Every downstream consumer of an identifier in this platform — the policy - * catalog, the descriptor, the observability convention, the admin snapshot — assumes the name is - * canonical, and the only place that assumption can be established is where the name is made. - */ -public record GrpcServiceName(String value) { - - private static final Pattern CANONICAL = - Pattern.compile("[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*\\.[A-Z][A-Za-z0-9_]*"); - - /** Validates the canonical form. */ - public GrpcServiceName { - GrpcIdentifiers.requireBounded(value, "service name"); - if (!CANONICAL.matcher(value).matches()) { - throw new IllegalArgumentException( - "service name must be a fully qualified proto name 'package.Service'; got '" - + value - + "'"); - } - } - - /** The proto package this service is declared in. */ - public String protoPackage() { - return value.substring(0, value.lastIndexOf('.')); - } - - /** The unqualified service name. */ - public String simpleName() { - return value.substring(value.lastIndexOf('.') + 1); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStatusCode.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStatusCode.java deleted file mode 100644 index 3c1a6328..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStatusCode.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.grpc.core; - -/** - * The canonical gRPC status codes, mirrored so that {@code grpc-core-api} stays free of io.grpc. - * - *

The mirror is the point. The Stable plan requires the evidence and failure model to be - * framework-free, and a failure context that names {@code io.grpc.Status} would put the transport - * inside the contract that exists to describe what the transport did. {@code grpc-runtime} owns the - * translation in both directions and is tested against the real enum. - */ -public enum GrpcStatusCode { - OK(0), - CANCELLED(1), - UNKNOWN(2), - INVALID_ARGUMENT(3), - DEADLINE_EXCEEDED(4), - NOT_FOUND(5), - ALREADY_EXISTS(6), - PERMISSION_DENIED(7), - RESOURCE_EXHAUSTED(8), - FAILED_PRECONDITION(9), - ABORTED(10), - OUT_OF_RANGE(11), - UNIMPLEMENTED(12), - INTERNAL(13), - UNAVAILABLE(14), - DATA_LOSS(15), - UNAUTHENTICATED(16); - - private final int value; - - GrpcStatusCode(int value) { - this.value = value; - } - - /** The wire value, identical to {@code io.grpc.Status.Code#value()}. */ - public int value() { - return value; - } - - /** - * Whether this code, on its own, says the server never began the work. - * - *

Only {@link #UNAVAILABLE} at connect time and {@link #CANCELLED} before send have that - * meaning, and neither is decidable from the code alone — which is why this returns false for - * every code. It exists so a caller that wants to ask "is this safe to replay" is pushed to the - * evidence model instead of reading safety out of a status. - */ - public boolean provesNotStarted() { - return false; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/RpcType.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/RpcType.java deleted file mode 100644 index 684bba20..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/RpcType.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.grpc.core; - -/** - * The four gRPC method shapes. - * - *

Only {@link #UNARY} and {@link #SERVER_STREAMING} are Stable. Client and bidirectional - * streaming are Advanced capabilities: they exist in this enum because a descriptor can name them - * and a policy has to be able to refuse them, not because the Stable platform serves them. - */ -public enum RpcType { - /** One request, one response. */ - UNARY(false, false), - /** One request, a bounded stream of responses. */ - SERVER_STREAMING(false, true), - /** A stream of requests, one response. Advanced. */ - CLIENT_STREAMING(true, false), - /** Streams in both directions. Advanced. */ - BIDI_STREAMING(true, true); - - private final boolean clientStreaming; - private final boolean serverStreaming; - - RpcType(boolean clientStreaming, boolean serverStreaming) { - this.clientStreaming = clientStreaming; - this.serverStreaming = serverStreaming; - } - - /** Whether the client sends more than one message. */ - public boolean clientStreaming() { - return clientStreaming; - } - - /** Whether the server sends more than one message. */ - public boolean serverStreaming() { - return serverStreaming; - } - - /** Whether either direction streams. */ - public boolean streaming() { - return clientStreaming || serverStreaming; - } - - /** - * Whether the Stable platform serves this shape. - * - *

The Stable scope is Unary and Server Streaming. A Stable component that is handed anything - * else must refuse it rather than degrade: partially supporting client streaming is how a - * platform ends up with a delivery guarantee nobody wrote down. - */ - public boolean stable() { - return !clientStreaming; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcBusinessEvidence.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcBusinessEvidence.java deleted file mode 100644 index a6b8791c..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcBusinessEvidence.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.grpc.evidence; - -/** - * What is known about the business effect — the second evidence axis. - * - *

Kept separate from the transport axis because the two genuinely disagree in the case that - * matters: a mutation whose transaction committed and whose response was lost is {@link - * #COMMIT_CONFIRMED} at the server and {@link #COMMIT_UNKNOWN} at the client, and no status code - * distinguishes those from a mutation that never ran. - */ -public enum GrpcBusinessEvidence { - /** No business work was attempted. */ - NONE, - /** The server accepted the call and began application work. */ - ATTEMPTED, - /** The application confirmed a durable commit. */ - COMMIT_CONFIRMED, - /** Work may or may not have committed. This is a real state, not a placeholder. */ - COMMIT_UNKNOWN, - /** The application refused the request; nothing was committed. */ - REJECTED; - - /** - * Whether a retry may run the business operation again without an idempotency guard. - * - *

{@link #COMMIT_UNKNOWN} answers false — which is the whole reason the value exists. - */ - public boolean safeToRepeatWithoutGuard() { - return this == NONE || this == REJECTED; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidence.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidence.java deleted file mode 100644 index 2bbd1b76..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidence.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.grpc.evidence; - -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; - -/** - * The three evidence axes for one RPC attempt, held together and never collapsed. - * - *

The same type is used by the failure model and by the observation convention. That is - * deliberate: when the exception and the metric are built from different snapshots of what - * happened, the incident review has two accounts of one call and no way to choose between them. - */ -public record GrpcExecutionEvidence( - GrpcMethodName method, - RpcType rpcType, - GrpcTransportEvidence transport, - GrpcBusinessEvidence business, - GrpcStreamEvidence stream) { - - /** Rejects combinations that cannot have been observed. */ - public GrpcExecutionEvidence { - if (method == null) { - throw new IllegalArgumentException("evidence requires a method"); - } - if (rpcType == null || transport == null || business == null || stream == null) { - throw new IllegalArgumentException("every evidence axis must be present"); - } - if (rpcType == RpcType.UNARY && stream.delivered()) { - throw new IllegalArgumentException( - "a unary call cannot carry stream evidence; got " + stream); - } - if (transport == GrpcTransportEvidence.NOT_SENT && business != GrpcBusinessEvidence.NONE) { - throw new IllegalArgumentException( - "a request the client never sent cannot carry business evidence " + business); - } - } - - /** A not-yet-started attempt. */ - public static GrpcExecutionEvidence notStarted(GrpcMethodName method, RpcType rpcType) { - return new GrpcExecutionEvidence( - method, - rpcType, - GrpcTransportEvidence.NOT_SENT, - GrpcBusinessEvidence.NONE, - GrpcStreamEvidence.none()); - } - - /** - * Records that response headers arrived, leaving the business axis exactly as it was. - * - *

This is the promotion the plan forbids, written as the one method that is allowed to observe - * headers — so the forbidden edit is visible as a change to this method rather than as a - * plausible line somewhere in an interceptor. - */ - public GrpcExecutionEvidence withResponseHeadersSeen() { - return new GrpcExecutionEvidence( - method, rpcType, GrpcTransportEvidence.RESPONSE_HEADERS_SEEN, business, stream); - } - - /** Records a confirmed commit, which only the application may assert. */ - public GrpcExecutionEvidence withCommitConfirmed() { - return new GrpcExecutionEvidence( - method, rpcType, transport, GrpcBusinessEvidence.COMMIT_CONFIRMED, stream); - } - - /** Records that the outcome of the business work is unknown. */ - public GrpcExecutionEvidence withCommitUnknown() { - return new GrpcExecutionEvidence( - method, rpcType, transport, GrpcBusinessEvidence.COMMIT_UNKNOWN, stream); - } - - /** Replaces the stream axis. */ - public GrpcExecutionEvidence withStream(GrpcStreamEvidence replacement) { - return new GrpcExecutionEvidence(method, rpcType, transport, business, replacement); - } - - /** - * Whether a whole-call transparent retry is permitted by the evidence alone. - * - *

Evidence alone is never sufficient — the idempotency profile and the retry owner also have a - * say — but it is sufficient to refuse, and refusing here keeps the three reasons to refuse from - * having to be re-derived at every call site. - */ - public boolean permitsWholeCallRetry() { - return !stream.delivered() && business.safeToRepeatWithoutGuard(); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcStreamEvidence.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcStreamEvidence.java deleted file mode 100644 index f827a98e..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcStreamEvidence.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.grpc.evidence; - -/** - * What a stream delivered — the third evidence axis. - * - *

A sealed hierarchy rather than an enum because three of the four states carry a position, and - * a position is the only thing that makes stream evidence actionable: "partial" without a last - * sequence cannot be resumed and cannot be reconciled, so it degrades to "something happened". - */ -public sealed interface GrpcStreamEvidence { - - /** No stream was involved. The only legal value for a unary call. */ - record None() implements GrpcStreamEvidence {} - - /** - * The stream delivered messages up to {@code lastSequence} and then ended without completing. - * - *

Its presence forbids a whole-call transparent retry: the client already saw a prefix, and - * replaying the call would deliver that prefix twice. - */ - record Partial(long lastSequence) implements GrpcStreamEvidence { - /** Rejects a sequence that cannot have been observed. */ - public Partial { - if (lastSequence < 0) { - throw new IllegalArgumentException("last sequence must not be negative"); - } - } - } - - /** - * The consumer acknowledged applying messages up to {@code lastAppliedSequence}. - * - *

Requires a named acknowledgement source. The Stable plan forbids synthesising this state - * from transport progress, and a required non-blank source is what makes that forgery visible: - * there is nowhere to put "the writer returned from onNext". - */ - record Applied(long lastAppliedSequence, String acknowledgementSource) - implements GrpcStreamEvidence { - /** Requires a real acknowledgement source. */ - public Applied { - if (lastAppliedSequence < 0) { - throw new IllegalArgumentException("last applied sequence must not be negative"); - } - if (acknowledgementSource == null || acknowledgementSource.isBlank()) { - throw new IllegalArgumentException( - "APPLIED requires a named application acknowledgement source; transport progress is " - + "not an acknowledgement"); - } - } - } - - /** - * The stream ended at {@code lastSequence} and can be continued with {@code - * resumeTokenReference}. - * - *

The reference is an opaque handle, never the token itself: a resume token carries a signed - * actor, tenant and filter fingerprint, and evidence is a thing that gets logged. - */ - record Resumable(long lastSequence, String resumeTokenReference) implements GrpcStreamEvidence { - /** Requires a position and an opaque handle. */ - public Resumable { - if (lastSequence < 0) { - throw new IllegalArgumentException("last sequence must not be negative"); - } - if (resumeTokenReference == null || resumeTokenReference.isBlank()) { - throw new IllegalArgumentException("a resumable stream needs a resume token reference"); - } - } - } - - /** The canonical "no stream" value. */ - static GrpcStreamEvidence none() { - return new None(); - } - - /** Whether any message was delivered, which is what forbids a whole-call retry. */ - default boolean delivered() { - return !(this instanceof None); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcTransportEvidence.java b/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcTransportEvidence.java deleted file mode 100644 index c9863699..00000000 --- a/src/platforms/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/evidence/GrpcTransportEvidence.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.grpc.evidence; - -/** - * What the transport was observed to do — the first of the three independent evidence axes. - * - *

Every value here is an observation, never an inference. The distinction that matters is - * between {@link #NOT_SENT}, which means the client watched the send fail, and {@link #UNOBSERVED}, - * which means nobody knows. Collapsing the second into the first is the mistake this axis exists to - * prevent: it turns "we do not know whether the server got the request" into "the server did not - * get the request", and that is the reasoning that replays a payment. - */ -public enum GrpcTransportEvidence { - /** The client observed the send fail before any byte reached the wire. */ - NOT_SENT, - /** Bytes left the client. Nothing is known about what the server did with them. */ - SENT_UNCONFIRMED, - /** Response headers arrived. This says the server started; it does not say it committed. */ - RESPONSE_HEADERS_SEEN, - /** At least one response message arrived. */ - RESPONSE_MESSAGE_SEEN, - /** Trailers arrived, so the call completed at the transport level. */ - TRAILERS_SEEN, - /** The call ended without the client observing enough to place it above. */ - UNOBSERVED; - - /** - * Whether the client saw the server begin producing a response. - * - *

Deliberately not named anything with "success" or "committed" in it. Response headers are a - * transport fact, and the only business meaning they carry is the one the business axis records - * separately. - */ - public boolean serverResponded() { - return this == RESPONSE_HEADERS_SEEN || this == RESPONSE_MESSAGE_SEEN || this == TRAILERS_SEEN; - } - - /** Whether this observation, alone, rules out the server having started the work. */ - public boolean provesNotStarted() { - return this == NOT_SENT; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudgetTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudgetTest.java deleted file mode 100644 index 8241a1dc..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudgetTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package dev.caskeleton.grpc.api.context; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.api.deadline.GrpcCancellationToken; -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineBudget; -import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcMetadataBudgetTest { - - private static final GrpcMethodName GET = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - private static final GrpcMetadataKey CORRELATION = GrpcMetadataKey.ascii("x-correlation-id"); - private static final GrpcMetadataKey IDEMPOTENCY = GrpcMetadataKey.ascii("x-idempotency-key"); - - private static GrpcDeadlineBudget budget() { - return GrpcDeadlineBudget.forEntryPoint( - Duration.ofSeconds(1), GrpcDeadlineProfile.of(Duration.ofSeconds(2))); - } - - @Test - @DisplayName("a metadata key may not borrow the reserved grpc- prefix") - void reservedPrefixIsRefused() { - assertThatThrownBy(() -> GrpcMetadataKey.ascii("grpc-tenant")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("reserved"); - } - - @Test - @DisplayName("binary keys end in -bin and ASCII keys do not") - void binarySuffixMatchesTheKind() { - assertThat(GrpcMetadataKey.binary("trace-state-bin").kind()) - .isEqualTo(GrpcMetadataKey.Kind.BINARY); - assertThatThrownBy(() -> GrpcMetadataKey.binary("trace-state")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> GrpcMetadataKey.ascii("trace-state-bin")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("uppercase and control-character keys are refused") - void nonCanonicalKeysAreRefused() { - assertThatThrownBy(() -> GrpcMetadataKey.ascii("X-Correlation-Id")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> GrpcMetadataKey.ascii("")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the user-defined allowance is separate from, and never exceeds, the hard total") - void userDefinedAllowanceIsSeparateFromTheHardTotal() { - GrpcMetadataBudget standard = GrpcMetadataBudget.standard(); - - assertThat(standard.maxUserDefinedBytes()).isLessThan(standard.maxTotalBytes()); - assertThatThrownBy(() -> new GrpcMetadataBudget(1024, 2048, 8)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cannot exceed the hard total"); - } - - @Test - @DisplayName("the budget is checked before the call starts, naming the bound that was exceeded") - void budgetIsCheckedBeforeTheCallStarts() { - GrpcMetadataBudget tight = new GrpcMetadataBudget(200, 40, 4); - Map oversized = new LinkedHashMap<>(); - oversized.put(CORRELATION, "x".repeat(64)); - - assertThatThrownBy(() -> tight.check(oversized)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("user-defined metadata"); - - Map tooManyEntries = new LinkedHashMap<>(); - tooManyEntries.put(CORRELATION, "a"); - tooManyEntries.put(IDEMPOTENCY, "b"); - tooManyEntries.put(GrpcMetadataKey.ascii("x-a"), "c"); - tooManyEntries.put(GrpcMetadataKey.ascii("x-b"), "d"); - tooManyEntries.put(GrpcMetadataKey.ascii("x-c"), "e"); - assertThatThrownBy(() -> tight.check(tooManyEntries)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("entries"); - } - - @Test - @DisplayName("a request context keeps only allowlisted metadata and refuses the rest loudly") - void requestContextRefusesMetadataOutsideTheAllowlist() { - Map inbound = - Map.of(CORRELATION, "corr-1", GrpcMetadataKey.ascii("x-tenant-claim"), "other-tenant"); - - assertThatThrownBy( - () -> - GrpcRequestContext.create( - GET, - RpcType.UNARY, - GrpcClientIdentity.anonymous(), - budget(), - new GrpcCancellationToken(), - inbound, - Set.of(CORRELATION), - GrpcMetadataBudget.standard(), - null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("x-tenant-claim") - .hasMessageContaining("allowlist"); - } - - @Test - @DisplayName("a request context exposes no raw metadata map and is immutable once built") - void requestContextIsImmutable() { - Map inbound = new LinkedHashMap<>(); - inbound.put(CORRELATION, "corr-1"); - - GrpcRequestContext context = - GrpcRequestContext.create( - GET, - RpcType.UNARY, - GrpcClientIdentity.fromVerifiedAuthentication("actor-1", "tenant-1", "jwt-issuer"), - budget(), - new GrpcCancellationToken(), - inbound, - Set.of(CORRELATION), - GrpcMetadataBudget.standard(), - "trace-1"); - - inbound.put(IDEMPOTENCY, "leaked-after-the-fact"); - - assertThat(context.metadata()).containsOnlyKeys(CORRELATION); - assertThat(context.metadataValue(CORRELATION)).contains("corr-1"); - assertThat(context.metadataValue(IDEMPOTENCY)).isEmpty(); - assertThat(context.traceId()).contains("trace-1"); - assertThat(context.live()).isTrue(); - } - - @Test - @DisplayName("identity names the verifier that established it") - void identityNamesItsVerifier() { - GrpcClientIdentity identity = - GrpcClientIdentity.fromVerifiedAuthentication("actor-1", "tenant-1", "mtls-peer-subject"); - - assertThat(identity.authenticationSource()).isEqualTo("mtls-peer-subject"); - assertThatThrownBy( - () -> GrpcClientIdentity.fromVerifiedAuthentication("actor-1", "tenant-1", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("authentication source"); - } - - @Test - @DisplayName("a cancelled or expired context is not live") - void cancelledContextIsNotLive() { - GrpcCancellationToken token = new GrpcCancellationToken(); - GrpcRequestContext context = - GrpcRequestContext.create( - GET, - RpcType.UNARY, - GrpcClientIdentity.anonymous(), - budget(), - token, - Map.of(), - Set.of(), - GrpcMetadataBudget.standard(), - null); - - token.cancel("client-cancelled", java.time.Instant.parse("2026-08-30T10:00:00Z")); - - assertThat(context.live()).isFalse(); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudgetTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudgetTest.java deleted file mode 100644 index a23bc99c..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudgetTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package dev.caskeleton.grpc.api.deadline; - -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 java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcDeadlineBudgetTest { - - private static final GrpcDeadlineProfile TWO_SECONDS = - GrpcDeadlineProfile.of(Duration.ofSeconds(2)); - - @Test - @DisplayName("a Stable unary call without a propagated deadline is refused") - void unaryEntryPointRequiresAPositiveDeadline() { - assertThatThrownBy(() -> GrpcDeadlineBudget.forEntryPoint(null, TWO_SECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("positive deadline"); - assertThatThrownBy(() -> GrpcDeadlineBudget.forEntryPoint(Duration.ZERO, TWO_SECONDS)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the budget takes the shorter of the parent remaining and the method default") - void budgetTakesTheShorterOfParentAndMethodDefault() { - GrpcDeadlineBudget fromShortParent = - GrpcDeadlineBudget.forEntryPoint( - Duration.ofMillis(500), TWO_SECONDS, GrpcDeadlineBudgetTest::frozenNanos); - GrpcDeadlineBudget fromLongParent = - GrpcDeadlineBudget.forEntryPoint( - Duration.ofSeconds(30), TWO_SECONDS, GrpcDeadlineBudgetTest::frozenNanos); - - assertThat(fromShortParent.remaining()) - .isEqualTo(Duration.ofMillis(500).minus(TWO_SECONDS.safetyMargin())); - assertThat(fromLongParent.remaining()) - .isEqualTo(TWO_SECONDS.total().minus(TWO_SECONDS.safetyMargin())); - } - - @Test - @DisplayName("the safety reserve is subtracted so serialization and trailers have room") - void safetyReserveIsSubtracted() { - GrpcDeadlineProfile profile = - new GrpcDeadlineProfile( - Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofMillis(100)); - - GrpcDeadlineBudget budget = - GrpcDeadlineBudget.forEntryPoint( - Duration.ofSeconds(10), profile, GrpcDeadlineBudgetTest::frozenNanos); - - assertThat(budget.remaining()).isEqualTo(Duration.ofSeconds(9)); - assertThat(profile.usable()).isEqualTo(Duration.ofSeconds(9)); - } - - @Test - @DisplayName("a downstream call never gets more time than its caller has left") - void downstreamNeverExceedsTheCaller() { - GrpcDeadlineBudget caller = - GrpcDeadlineBudget.forEntryPoint( - Duration.ofMillis(400), TWO_SECONDS, GrpcDeadlineBudgetTest::frozenNanos); - GrpcDeadlineProfile generousDownstream = - new GrpcDeadlineProfile(Duration.ofSeconds(30), Duration.ZERO, Duration.ofMillis(10)); - - GrpcDeadlineBudget downstream = caller.deriveDownstream(generousDownstream); - - assertThat(downstream.remaining()).isLessThanOrEqualTo(caller.remaining()); - } - - @Test - @DisplayName("a dependency call is not started with less than the minimum attempt budget") - void dependencyCallIsRefusedBelowTheMinimumAttemptBudget() { - GrpcDeadlineProfile profile = - new GrpcDeadlineProfile( - Duration.ofSeconds(1), Duration.ofMillis(100), Duration.ofMillis(250)); - - assertThat(new GrpcDeadlineBudget(Duration.ofMillis(300), profile).canStartDependencyCall()) - .isTrue(); - assertThat(new GrpcDeadlineBudget(Duration.ofMillis(100), profile).canStartDependencyCall()) - .isFalse(); - assertThat(new GrpcDeadlineBudget(Duration.ZERO, profile).canStartDependencyCall()).isFalse(); - } - - @Test - void aBudgetRunsOutAsTimePassesAfterItWasCreated() { - // given - AtomicLong nanos = new AtomicLong(); - GrpcDeadlineBudget budget = - new GrpcDeadlineBudget(Duration.ofMillis(300), TWO_SECONDS, nanos::get); - - // when - nanos.addAndGet(Duration.ofMillis(300).toNanos()); - - // then - assertThat(budget) - .extracting(GrpcDeadlineBudget::remaining, GrpcDeadlineBudget::expired) - .containsExactly(Duration.ZERO, true); - } - - @Test - void aDownstreamDerivedLaterGetsOnlyWhatIsLeftThen() { - // given - AtomicLong nanos = new AtomicLong(); - GrpcDeadlineBudget caller = - new GrpcDeadlineBudget(Duration.ofSeconds(1), TWO_SECONDS, nanos::get); - nanos.addAndGet(Duration.ofMillis(700).toNanos()); - - // when - GrpcDeadlineBudget downstream = - caller.deriveDownstream( - new GrpcDeadlineProfile(Duration.ofSeconds(30), Duration.ZERO, Duration.ofMillis(10))); - - // then - assertThat(downstream.remaining()).isEqualTo(Duration.ofMillis(300)); - } - - @Test - @DisplayName("a profile whose reserve leaves no usable time is refused") - void profileWithNoUsableTimeIsRefused() { - assertThatThrownBy( - () -> - new GrpcDeadlineProfile( - Duration.ofSeconds(1), Duration.ofSeconds(1), Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("leaves no time"); - assertThatThrownBy(() -> GrpcDeadlineProfile.of(Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("cancellation is idempotent and keeps the first reason") - void cancellationIsIdempotentAndKeepsTheFirstReason() { - GrpcCancellationToken token = new GrpcCancellationToken(); - Instant first = Instant.parse("2026-08-30T10:00:00Z"); - - assertThat(token.cancel("client-cancelled", first)).isTrue(); - assertThat(token.cancel("server-drain", first.plusSeconds(1))).isFalse(); - - assertThat(token.cancelled()).isTrue(); - assertThat(token.cancellation()) - .hasValueSatisfying( - c -> { - assertThat(c.reason()).isEqualTo("client-cancelled"); - assertThat(c.at()).isEqualTo(first); - }); - } - - @Test - @DisplayName("a cancelled call refuses to start a new side effect") - void cancelledCallRefusesANewSideEffect() { - GrpcCancellationToken token = new GrpcCancellationToken(); - token.requireNotCancelled("charge-card"); - - token.cancel("deadline-exceeded", Instant.parse("2026-08-30T10:00:00Z")); - - assertThatThrownBy(() -> token.requireNotCancelled("charge-card")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("charge-card") - .hasMessageContaining("deadline-exceeded"); - } - - private static long frozenNanos() { - return 0L; - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/error/GrpcFailureContextTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/error/GrpcFailureContextTest.java deleted file mode 100644 index c56aff7a..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/error/GrpcFailureContextTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package dev.caskeleton.grpc.api.error; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.GrpcStatusCode; -import dev.caskeleton.grpc.core.RpcType; -import dev.caskeleton.grpc.evidence.GrpcBusinessEvidence; -import dev.caskeleton.grpc.evidence.GrpcExecutionEvidence; -import dev.caskeleton.grpc.evidence.GrpcStreamEvidence; -import dev.caskeleton.grpc.evidence.GrpcTransportEvidence; -import java.time.Duration; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcFailureContextTest { - - private static final GrpcMethodName CREATE = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); - private static final GrpcMethodName WATCH = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); - - private static GrpcExecutionEvidence sentButUnanswered() { - return new GrpcExecutionEvidence( - CREATE, - RpcType.UNARY, - GrpcTransportEvidence.SENT_UNCONFIRMED, - GrpcBusinessEvidence.ATTEMPTED, - GrpcStreamEvidence.none()); - } - - @Test - @DisplayName("a deadline on a mutation is COMPLETION_UNKNOWN, not a rejection") - void deadlineOnAMutationIsCompletionUnknown() { - GrpcCompletionOutcome outcome = - GrpcCompletionOutcome.forMutation(GrpcStatusCode.DEADLINE_EXCEEDED, sentButUnanswered()); - - assertThat(outcome).isEqualTo(GrpcCompletionOutcome.COMPLETION_UNKNOWN); - assertThat(outcome.requiresReconciliation()).isTrue(); - } - - @Test - @DisplayName("UNAVAILABLE alone does not make a mutation safe to re-issue") - void unavailableAloneDoesNotMakeAMutationRepeatable() { - assertThat(GrpcCompletionOutcome.forMutation(GrpcStatusCode.UNAVAILABLE, sentButUnanswered())) - .isEqualTo(GrpcCompletionOutcome.COMPLETION_UNKNOWN); - } - - @Test - @DisplayName("a send the client watched fail is a rejection, because nothing ran") - void observedFailedSendIsARejection() { - GrpcExecutionEvidence notSent = GrpcExecutionEvidence.notStarted(CREATE, RpcType.UNARY); - - assertThat(GrpcCompletionOutcome.forMutation(GrpcStatusCode.UNAVAILABLE, notSent)) - .isEqualTo(GrpcCompletionOutcome.REJECTED); - } - - @Test - @DisplayName("a confirmed commit outranks whatever status the transport reported") - void confirmedCommitOutranksTheStatus() { - GrpcExecutionEvidence committed = sentButUnanswered().withCommitConfirmed(); - - assertThat(GrpcCompletionOutcome.forMutation(GrpcStatusCode.DEADLINE_EXCEEDED, committed)) - .isEqualTo(GrpcCompletionOutcome.COMPLETED); - } - - @Test - @DisplayName("a delivered stream prefix is PARTIAL_STREAM") - void deliveredStreamPrefixIsPartialStream() { - GrpcExecutionEvidence partial = - new GrpcExecutionEvidence( - WATCH, - RpcType.SERVER_STREAMING, - GrpcTransportEvidence.RESPONSE_MESSAGE_SEEN, - GrpcBusinessEvidence.NONE, - new GrpcStreamEvidence.Partial(9L)); - - assertThat(GrpcCompletionOutcome.forMutation(GrpcStatusCode.UNAVAILABLE, partial)) - .isEqualTo(GrpcCompletionOutcome.PARTIAL_STREAM); - } - - @Test - @DisplayName("the redacted summary carries identity and timing, never payload or credentials") - void redactedSummaryCarriesNoSecrets() { - GrpcFailureContext context = - new GrpcFailureContext( - CREATE, - GrpcStatusCode.DEADLINE_EXCEEDED, - GrpcFailureCategory.DEADLINE, - sentButUnanswered(), - GrpcCompletionOutcome.COMPLETION_UNKNOWN, - GrpcFailureContext.RetryDisposition.RESOLVE_FIRST, - 2, - Duration.ofMillis(1500), - Optional.of("trace-abc")); - - String summary = context.redactedSummary(); - - assertThat(summary) - .contains("caskeleton.document.v1.DocumentService/CreateDocument") - .contains("DEADLINE_EXCEEDED") - .contains("COMPLETION_UNKNOWN") - .contains("RESOLVE_FIRST") - .contains("elapsedMs=1500") - .contains("trace-abc"); - } - - @Test - @DisplayName("a failure context whose method disagrees with its evidence is refused") - void methodMustAgreeWithEvidence() { - assertThatThrownBy( - () -> - new GrpcFailureContext( - WATCH, - GrpcStatusCode.INTERNAL, - GrpcFailureCategory.INTERNAL, - sentButUnanswered(), - GrpcCompletionOutcome.COMPLETION_UNKNOWN, - GrpcFailureContext.RetryDisposition.NOT_RETRYABLE, - 1, - Duration.ZERO, - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("disagrees with its evidence"); - } - - @Test - @DisplayName( - "the platform exception says only what the redacted summary says, and keeps the cause") - void platformExceptionMessageIsTheRedactedSummary() { - GrpcFailureContext context = - new GrpcFailureContext( - CREATE, - GrpcStatusCode.INTERNAL, - GrpcFailureCategory.PERMANENT_DEPENDENCY, - sentButUnanswered(), - GrpcCompletionOutcome.COMPLETION_UNKNOWN, - GrpcFailureContext.RetryDisposition.RESOLVE_FIRST, - 1, - Duration.ofMillis(10), - Optional.empty()); - Exception driverFailure = new IllegalStateException("ERROR: duplicate key value violates ..."); - - GrpcPlatformException exception = new GrpcPlatformException(context, driverFailure); - - assertThat(exception).hasMessage(context.redactedSummary()); - assertThat(exception.getMessage()).doesNotContain("duplicate key"); - assertThat(exception).hasCause(driverFailure); - assertThat(exception.requiresReconciliation()).isTrue(); - } - - @Test - @DisplayName("every failure category maps to a canonical status code") - void everyCategoryMapsToAStatusCode() { - assertThat(GrpcFailureCategory.values()) - .allSatisfy(c -> assertThat(c.statusCode()).isNotNull()); - assertThat(GrpcFailureCategory.VALIDATION.statusCode()) - .isEqualTo(GrpcStatusCode.INVALID_ARGUMENT); - assertThat(GrpcFailureCategory.TRANSIENT_DEPENDENCY.transientFailure()).isTrue(); - assertThat(GrpcFailureCategory.PERMANENT_DEPENDENCY.transientFailure()).isFalse(); - } - - @Test - @DisplayName("an attempt counter below one is refused") - void attemptIsOneBased() { - assertThatThrownBy( - () -> - new GrpcFailureContext( - CREATE, - GrpcStatusCode.INTERNAL, - GrpcFailureCategory.INTERNAL, - sentButUnanswered(), - GrpcCompletionOutcome.COMPLETION_UNKNOWN, - GrpcFailureContext.RetryDisposition.TERMINAL, - 0, - Duration.ZERO, - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentityTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentityTest.java deleted file mode 100644 index 2701a083..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentityTest.java +++ /dev/null @@ -1,44 +0,0 @@ -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 dev.caskeleton.grpc.core.GrpcServiceName; -import org.junit.jupiter.api.Test; - -class GrpcOperationIdentityTest { - - private static final GrpcMethodName CREATE = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); - private static final String KEY_HASH = - "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"; - - @Test - void aCallerFingerprintWiderThanItsLedgerColumnIsRefused() { - // when - Throwable failure = - catchThrowable(() -> new GrpcOperationIdentity("c".repeat(257), CREATE, KEY_HASH)); - - // then - assertThat(failure) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("caller fingerprint must be at most 256"); - } - - @Test - void anIdentityWhoseStorageKeyWouldNotFitTheLedgerIsRefused() { - // given - GrpcMethodName longMethod = - new GrpcMethodName(new GrpcServiceName("p.S" + "s".repeat(197)), "M" + "m".repeat(54)); - - // when - Throwable failure = - catchThrowable(() -> new GrpcOperationIdentity("c".repeat(256), longMethod, KEY_HASH)); - - // then - assertThat(failure) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("storage key must be at most 512"); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java deleted file mode 100644 index ff2916f1..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java +++ /dev/null @@ -1,11 +0,0 @@ -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/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalogTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalogTest.java deleted file mode 100644 index 738c8718..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalogTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package dev.caskeleton.grpc.api.policy; - -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.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import java.time.Duration; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcMethodPolicyCatalogTest { - - private static final GrpcMethodName GET = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - private static final GrpcMethodName CREATE = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); - private static final GrpcMethodName WATCH = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); - private static final GrpcDeadlineProfile TWO_SECONDS = - GrpcDeadlineProfile.of(Duration.ofSeconds(2)); - - @Test - @DisplayName("the idempotency profile has exactly the six documented values") - void idempotencyProfileHasSixValues() { - assertThat(RpcIdempotencyProfile.values()) - .containsExactly( - RpcIdempotencyProfile.READ_ONLY, - RpcIdempotencyProfile.NATURALLY_IDEMPOTENT, - RpcIdempotencyProfile.IDEMPOTENCY_KEY_REQUIRED, - RpcIdempotencyProfile.CONDITIONALLY_IDEMPOTENT, - RpcIdempotencyProfile.NON_IDEMPOTENT, - RpcIdempotencyProfile.STREAMING); - } - - @Test - @DisplayName("only a read-only unary method may be hedged") - void onlyReadOnlyUnaryMayBeHedged() { - assertThat(GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS).hedgingAllowed()).isTrue(); - assertThat(GrpcMethodPolicy.nonIdempotentUnary(CREATE, TWO_SECONDS).hedgingAllowed()).isFalse(); - assertThat(RpcIdempotencyProfile.IDEMPOTENCY_KEY_REQUIRED.hedgingAllowed()).isFalse(); - } - - @Test - @DisplayName("attaching an explicit retry policy to a NON_IDEMPOTENT method fails to build") - void nonIdempotentMethodRejectsExplicitRetry() { - assertThatThrownBy( - () -> - new GrpcMethodPolicy( - CREATE, - RpcType.UNARY, - RpcIdempotencyProfile.NON_IDEMPOTENT, - TWO_SECONDS, - WaitForReadyPolicy.DISABLED, - true, - 1024, - 1024)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("NON_IDEMPOTENT") - .hasMessageContaining("explicit retry"); - } - - @Test - @DisplayName("a streaming method rejects a whole-call retry policy") - void streamingMethodRejectsWholeCallRetry() { - assertThatThrownBy( - () -> - new GrpcMethodPolicy( - WATCH, - RpcType.SERVER_STREAMING, - RpcIdempotencyProfile.STREAMING, - TWO_SECONDS, - WaitForReadyPolicy.DISABLED, - true, - 1024, - 1024)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("prefix"); - } - - @Test - @DisplayName("a unary method may not claim the STREAMING idempotency profile") - void unaryMethodMayNotClaimTheStreamingProfile() { - assertThatThrownBy( - () -> - new GrpcMethodPolicy( - GET, - RpcType.UNARY, - RpcIdempotencyProfile.STREAMING, - TWO_SECONDS, - WaitForReadyPolicy.DISABLED, - false, - 1024, - 1024)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("STREAMING profile"); - } - - @Test - @DisplayName("every Stable method carries a deadline profile") - void everyStableMethodCarriesADeadline() { - assertThatThrownBy( - () -> - new GrpcMethodPolicy( - GET, - RpcType.UNARY, - RpcIdempotencyProfile.READ_ONLY, - null, - WaitForReadyPolicy.DISABLED, - false, - 1024, - 1024)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("deadline profile"); - } - - @Test - @DisplayName("wait-for-ready is off by default") - void waitForReadyIsOffByDefault() { - assertThat(GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS).waitForReady()) - .isEqualTo(WaitForReadyPolicy.DISABLED); - assertThat(WaitForReadyPolicy.DISABLED.queues()).isFalse(); - assertThat(WaitForReadyPolicy.WORKER_OPT_IN.queues()).isTrue(); - } - - @Test - @DisplayName("registering the same method twice fails rather than picking a winner") - void duplicateRegistrationFails() { - GrpcMethodPolicyCatalog.Builder builder = - GrpcMethodPolicyCatalog.builder() - .register(GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS)); - - assertThatThrownBy(() -> builder.register(GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate method policy"); - } - - @Test - @DisplayName("a policy for a method the schema does not declare fails the catalog build") - void policyForAnUndeclaredMethodFailsTheBuild() { - GrpcMethodPolicyCatalog.Builder builder = - GrpcMethodPolicyCatalog.builder() - .withDescriptorMethods(Set.of(GET)) - .register(GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS)) - .register(GrpcMethodPolicy.nonIdempotentUnary(CREATE, TWO_SECONDS)); - - assertThatThrownBy(builder::build) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("CreateDocument"); - } - - @Test - @DisplayName("a method with no policy is refused rather than given defaults") - void missingPolicyIsRefusedRatherThanDefaulted() { - GrpcMethodPolicyCatalog catalog = - GrpcMethodPolicyCatalog.builder() - .register(GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS)) - .build(); - - assertThat(catalog.find(GET)).isPresent(); - assertThat(catalog.find(CREATE)).isEmpty(); - assertThat(catalog.size()).isEqualTo(1); - assertThatThrownBy(() -> catalog.require(CREATE)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no deadline and no idempotency profile"); - } - - @Test - @DisplayName("the descriptor and the catalog agree on one canonical spelling of a method") - void descriptorAndCatalogShareOneCanonicalName() { - GrpcMethodPolicyCatalog catalog = - GrpcMethodPolicyCatalog.builder() - .withDescriptorMethods(Set.of(GET, CREATE)) - .register(GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS)) - .build(); - - assertThat(catalog.methods()) - .extracting(GrpcMethodName::canonical) - .containsExactly("caskeleton.document.v1.DocumentService/GetDocument"); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcCoreIdentifiersTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcCoreIdentifiersTest.java deleted file mode 100644 index 7940d71a..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcCoreIdentifiersTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.grpc.core; - -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.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -class GrpcCoreIdentifiersTest { - - @Test - @DisplayName("a full method name round-trips through its canonical form") - void methodNameRoundTripsThroughCanonicalForm() { - GrpcMethodName parsed = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - - assertThat(parsed.canonical()).isEqualTo("caskeleton.document.v1.DocumentService/GetDocument"); - assertThat(parsed.method()).isEqualTo("GetDocument"); - assertThat(parsed.service().simpleName()).isEqualTo("DocumentService"); - assertThat(parsed.service().protoPackage()).isEqualTo("caskeleton.document.v1"); - assertThat(GrpcMethodName.parse(parsed.canonical())).isEqualTo(parsed); - } - - @ParameterizedTest - @ValueSource( - strings = { - "DocumentService/Get", - "caskeleton.document.v1.DocumentService", - "caskeleton.document.v1.DocumentService/Get/Extra", - "caskeleton.document.v1.DocumentService/getDocument" - }) - @DisplayName("a name that is not exactly package.Service/Method is refused") - void nonCanonicalMethodNamesAreRefused(String candidate) { - assertThatThrownBy(() -> GrpcMethodName.parse(candidate)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("생성자로 만든 full method name도 parse와 같은 256자 한도를 넘으면 거부된다") - void constructedMethodNameLongerThanTheParseLimitIsRefused() { - // given - GrpcServiceName service = new GrpcServiceName("pkg.v1." + "S".repeat(200)); - String method = "M".repeat(100); - - // when - Throwable thrown = catchThrowable(() -> new GrpcMethodName(service, method)); - - // then - assertThat(thrown) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("full method name must be at most 256 characters; got 308"); - } - - @ParameterizedTest - @ValueSource(strings = {"", "svc name", "Has Space", "tab\tseparated"}) - @DisplayName("blank, whitespace and control-character identifiers are refused") - void blankAndControlCharacterIdentifiersAreRefused(String candidate) { - assertThatThrownBy(() -> new GrpcServiceName(candidate)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GrpcChannelProfileName(candidate)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a channel profile name is lower-kebab-case") - void channelProfileNameIsLowerKebabCase() { - assertThat(new GrpcChannelProfileName("document-service-read").value()) - .isEqualTo("document-service-read"); - assertThatThrownBy(() -> new GrpcChannelProfileName("DocumentService")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("RpcType has exactly the four shapes, and only the two Stable ones are Stable") - void rpcTypeHasExactlyFourShapesAndTwoAreStable() { - assertThat(RpcType.values()) - .containsExactly( - RpcType.UNARY, - RpcType.SERVER_STREAMING, - RpcType.CLIENT_STREAMING, - RpcType.BIDI_STREAMING); - assertThat(RpcType.UNARY.stable()).isTrue(); - assertThat(RpcType.SERVER_STREAMING.stable()).isTrue(); - assertThat(RpcType.CLIENT_STREAMING.stable()).isFalse(); - assertThat(RpcType.BIDI_STREAMING.stable()).isFalse(); - assertThat(RpcType.UNARY.streaming()).isFalse(); - assertThat(RpcType.SERVER_STREAMING.streaming()).isTrue(); - } - - @Test - @DisplayName("no status code claims, on its own, that the server never started") - void statusCodeNeverProvesTheServerDidNotStart() { - assertThat(GrpcStatusCode.values()).noneMatch(GrpcStatusCode::provesNotStarted); - assertThat(GrpcStatusCode.DEADLINE_EXCEEDED.value()).isEqualTo(4); - assertThat(GrpcStatusCode.UNAVAILABLE.value()).isEqualTo(14); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidenceTest.java b/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidenceTest.java deleted file mode 100644 index 4b3b5283..00000000 --- a/src/platforms/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidenceTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.caskeleton.grpc.evidence; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcExecutionEvidenceTest { - - private static final GrpcMethodName CREATE = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); - private static final GrpcMethodName WATCH = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); - - @Test - @DisplayName("seeing response headers never promotes the business axis to a confirmed commit") - void responseHeadersAreNotPromotedToCommitConfirmed() { - GrpcExecutionEvidence attempted = - new GrpcExecutionEvidence( - CREATE, - RpcType.UNARY, - GrpcTransportEvidence.SENT_UNCONFIRMED, - GrpcBusinessEvidence.ATTEMPTED, - GrpcStreamEvidence.none()); - - GrpcExecutionEvidence afterHeaders = attempted.withResponseHeadersSeen(); - - assertThat(afterHeaders.transport()).isEqualTo(GrpcTransportEvidence.RESPONSE_HEADERS_SEEN); - assertThat(afterHeaders.business()).isEqualTo(GrpcBusinessEvidence.ATTEMPTED); - assertThat(afterHeaders.transport().serverResponded()).isTrue(); - } - - @Test - @DisplayName("a unary call may not carry stream evidence") - void unaryCallMayNotCarryStreamEvidence() { - assertThatThrownBy( - () -> - new GrpcExecutionEvidence( - CREATE, - RpcType.UNARY, - GrpcTransportEvidence.RESPONSE_MESSAGE_SEEN, - GrpcBusinessEvidence.ATTEMPTED, - new GrpcStreamEvidence.Partial(7L))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unary"); - } - - @Test - @DisplayName("a request that was never sent cannot carry business evidence") - void unsentRequestCannotCarryBusinessEvidence() { - assertThatThrownBy( - () -> - new GrpcExecutionEvidence( - CREATE, - RpcType.UNARY, - GrpcTransportEvidence.NOT_SENT, - GrpcBusinessEvidence.COMMIT_CONFIRMED, - GrpcStreamEvidence.none())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("APPLIED requires a named application acknowledgement, not transport progress") - void appliedRequiresAnApplicationAcknowledgement() { - assertThatThrownBy(() -> new GrpcStreamEvidence.Applied(4L, " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("acknowledgement"); - - GrpcStreamEvidence applied = new GrpcStreamEvidence.Applied(4L, "consumer-checkpoint-store"); - assertThat(applied.delivered()).isTrue(); - } - - @Test - @DisplayName("stream evidence is a closed set of four shapes") - void streamEvidenceIsAClosedSetOfFourShapes() { - assertThat(GrpcStreamEvidence.class.getPermittedSubclasses()) - .extracting(Class::getSimpleName) - .containsExactlyInAnyOrder("None", "Partial", "Applied", "Resumable"); - assertThat(GrpcStreamEvidence.none().delivered()).isFalse(); - } - - @Test - @DisplayName("a delivered stream prefix forbids a whole-call retry") - void deliveredStreamPrefixForbidsWholeCallRetry() { - GrpcExecutionEvidence partial = - new GrpcExecutionEvidence( - WATCH, - RpcType.SERVER_STREAMING, - GrpcTransportEvidence.RESPONSE_MESSAGE_SEEN, - GrpcBusinessEvidence.NONE, - new GrpcStreamEvidence.Partial(12L)); - - assertThat(partial.permitsWholeCallRetry()).isFalse(); - assertThat( - GrpcExecutionEvidence.notStarted(WATCH, RpcType.SERVER_STREAMING) - .permitsWholeCallRetry()) - .isTrue(); - } - - @Test - @DisplayName("an unknown commit is never safe to repeat without a guard") - void unknownCommitIsNeverSafeToRepeat() { - GrpcExecutionEvidence unknown = - GrpcExecutionEvidence.notStarted(CREATE, RpcType.UNARY) - .withResponseHeadersSeen() - .withCommitUnknown(); - - assertThat(unknown.business().safeToRepeatWithoutGuard()).isFalse(); - assertThat(unknown.permitsWholeCallRetry()).isFalse(); - } - - @Test - @DisplayName("evidence and its owning failure must name the same method") - void evidenceCarriesItsOwnMethod() { - assertThat(GrpcExecutionEvidence.notStarted(CREATE, RpcType.UNARY).method()).isEqualTo(CREATE); - } -} diff --git a/src/platforms/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java b/src/platforms/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java deleted file mode 100644 index ac84f97f..00000000 --- a/src/platforms/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java +++ /dev/null @@ -1,704 +0,0 @@ -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.Duration; -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 java.util.stream.Stream; -import org.junit.jupiter.api.DisplayName; -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("caskeleton.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"); - private static final Duration CLAIM_TTL = Duration.ofMinutes(5); - // A retry arriving after the TTL: its cutoff (LATER - TTL) is past the original claim at NOW. - private static final Instant LATER = NOW.plus(CLAIM_TTL).plusSeconds(1); - private static final Instant CUTOFF = LATER.minus(CLAIM_TTL); - // A purge run a day after NOW: rows finished around NOW are past retention. - private static final Instant RETENTION_CUTOFF = NOW.plus(Duration.ofDays(1)); - private static final GrpcOperationIdentity SECOND_ID = identityWithKeyHash('b'); - private static final GrpcOperationIdentity THIRD_ID = identityWithKeyHash('c'); - - /** 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, GrpcClaimToken.FIRST, 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, GrpcClaimToken.FIRST, OUTCOME, NOW)); - - // then - assertThat(refused) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no claim exists"); - } - - @Test - void aCommittedClaimCannotBeCommittedAgain() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); - - // when - Throwable refused = - catchThrowable( - () -> - ledger() - .markCommitted( - ID, GrpcClaimToken.FIRST, "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, GrpcClaimToken.FIRST, 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, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(2))); - - // then - assertThat(refused) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("cannot transition again"); - } - - @Test - void aFailedClaimIsReclaimedByARetryOfTheSameRequest() { - // given - failedClaim(); - - // when - Optional reclaimed = - ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); - - // then - assertThat(reclaimed).isPresent(); - } - - @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(); - GrpcClaimToken reclaimed = - ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)).orElseThrow(); - - // when - ledger().markCommitted(ID, reclaimed, 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))).isEmpty(); - } - - @Test - void anInProgressClaimIsNotReclaimed() { - ledger().claim(ID, FINGERPRINT, NOW); - - assertThat(ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(1))).isEmpty(); - } - - @Test - void aCommittedClaimIsNotReclaimed() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); - - // when - Optional reclaimed = - ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); - - // then - assertThat(reclaimed).isEmpty(); - } - - @Test - void concurrentReclaimsOfAFailedClaimHaveExactlyOneWinner() throws Exception { - // given - failedClaim(); - - // when - List reclaimed = - concurrently(() -> ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)).isPresent()); - - // then - assertThat(reclaimed).containsExactlyInAnyOrder(true, false); - } - - @Test - @DisplayName("TTL이 지난 IN_PROGRESS claim은 같은 요청의 재시도가 넘겨받는다") - void aStaleInProgressClaimIsTakenOverByARetryOfTheSameRequest() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // then - assertThat(reclaimed).isPresent(); - } - - @Test - @DisplayName("넘겨받은 stale claim은 넘겨받은 시각부터 진행 중인 새 시도다") - void aTakenOverStaleClaimIsANewAttemptInProgressSinceTheTakeover() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // then - assertThat(ledger().find(ID)) - .get() - .extracting( - GrpcOperationLedgerRecord::state, - GrpcOperationLedgerRecord::claimedAt, - GrpcOperationLedgerRecord::completedAt) - .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, LATER, Optional.empty()); - } - - @Test - @DisplayName("넘겨받은 stale claim은 commit할 수 있다") - void aTakenOverStaleClaimCanBeCommitted() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - GrpcClaimToken takenOver = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER).orElseThrow(); - - // when - ledger().markCommitted(ID, takenOver, OUTCOME, LATER.plusSeconds(1)); - - // then - assertThat(ledger().find(ID)) - .get() - .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::outcomeReference) - .containsExactly(GrpcOperationLedgerState.COMMITTED, Optional.of(OUTCOME)); - } - - @Test - @DisplayName("TTL 안의 IN_PROGRESS claim은 넘겨받지 않는다") - void anInProgressClaimWithinTheTtlIsNotTakenOver() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - Optional reclaimed = - ledger().reclaimStale(ID, FINGERPRINT, NOW, NOW.plus(CLAIM_TTL)); - - // then - assertThat(reclaimed).isEmpty(); - } - - @Test - @DisplayName("다른 요청은 TTL이 지난 claim도 넘겨받지 못한다") - void aStaleClaimIsNotTakenOverForADifferentRequest() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - Optional reclaimed = - ledger().reclaimStale(ID, OTHER_FINGERPRINT, CUTOFF, LATER); - - // then - assertThat(reclaimed).isEmpty(); - } - - @Test - @DisplayName("commit된 claim은 오래되어도 stale로 넘겨받지 않는다") - void aCommittedClaimIsNotTakenOverAsStale() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); - - // when - Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // then - assertThat(reclaimed).isEmpty(); - } - - @Test - @DisplayName("실패한 claim은 stale 회수가 아니라 실패 재claim으로만 다시 연다") - void aFailedClaimIsNotTakenOverAsStale() { - // given - failedClaim(); - - // when - Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // then - assertThat(reclaimed).isEmpty(); - } - - @Test - @DisplayName("claim이 없으면 stale 회수는 아무것도 만들지 않는다") - void takingOverAMissingClaimCreatesNothing() { - // when - Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // then - assertThat(reclaimed).isEmpty(); - assertThat(ledger().find(ID)).isEmpty(); - } - - @Test - @DisplayName("한 번 넘겨받은 claim은 같은 cutoff로 다시 넘겨받지 못한다") - void aTakenOverClaimIsNotTakenOverAgainWithTheSameCutoff() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // when - Optional again = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // then - assertThat(again).isEmpty(); - } - - @Test - @DisplayName("TTL이 지난 claim을 동시에 넘겨받으려 하면 승자는 하나다") - void concurrentTakeoversOfAStaleClaimHaveExactlyOneWinner() throws Exception { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - List reclaimed = - concurrently(() -> ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER).isPresent()); - - // then - assertThat(reclaimed).containsExactlyInAnyOrder(true, false); - } - - @Test - @DisplayName("cutoff가 현재 시각보다 뒤면 거부한다 — 새 claim이 곧바로 stale이 되기 때문이다") - void aCutoffAfterNowIsRefused() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - Throwable refused = catchThrowable(() -> ledger().reclaimStale(ID, FINGERPRINT, LATER, CUTOFF)); - - // then - assertThat(refused).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("cutoff"); - } - - @Test - @DisplayName("claim 을 넘겨받을 때마다 claim token 은 다음 시도 번호가 된다") - void eachHandOverIssuesTheNextClaimToken() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - GrpcClaimToken takenOver = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER).orElseThrow(); - - // then - assertThat(takenOver).isEqualTo(GrpcClaimToken.FIRST.next()); - assertThat(ledger().find(ID)) - .get() - .extracting(GrpcOperationLedgerRecord::claimToken) - .isEqualTo(takenOver); - } - - /** - * Release deletes the row, so it is fenced like every other transition: only the attempt that - * holds an unfinished claim may give it up (review 2026-11-03 RR-01-15). - */ - @Test - @DisplayName("진행 중 claim 을 가진 시도가 release 하면 키가 비고 다음 claim 이 첫 시도가 된다") - void releaseByTheAttemptHoldingAnUnfinishedClaimFreesTheKey() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - boolean released = ledger().release(ID, GrpcClaimToken.FIRST); - - // then - assertThat(List.of(released, ledger().claim(ID, FINGERPRINT, NOW.plusSeconds(1)).isEmpty())) - .containsExactly(true, true); - } - - @Test - @DisplayName("claim 을 넘겨준 옛 시도의 release 는 무시되고 새 시도의 claim 이 남는다") - void releaseByTheAttemptThatLostTheClaimChangesNothing() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // when - boolean released = ledger().release(ID, GrpcClaimToken.FIRST); - - // then - assertThat(released).isFalse(); - assertThat(ledger().find(ID)) - .get() - .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::claimToken) - .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, GrpcClaimToken.FIRST.next()); - } - - @Test - @DisplayName("끝난 claim 은 release 로 지워지지 않는다 — 재시도에 결과를 돌려줄 기록이다") - void releaseOfAFinishedClaimChangesNothing() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); - - // when - boolean released = ledger().release(ID, GrpcClaimToken.FIRST); - - // then - assertThat(released).isFalse(); - assertThat(ledger().find(ID)) - .get() - .extracting(GrpcOperationLedgerRecord::state) - .isEqualTo(GrpcOperationLedgerState.COMMITTED); - } - - /** - * The re-review probe's sequence (2026-11-03, RR-02-04): A claims and is slow, B takes the claim - * over after the TTL, then A reports a failure. Recording it would mark B's running attempt - * failed, and the next retry would re-claim it and run beside B. - */ - @Test - @DisplayName("TTL 뒤 넘겨받은 claim 에 옛 owner 가 실패를 기록하면 무시되고 새 시도는 진행 중으로 남는다") - void aFailureReportedByTheOwnerThatLostTheClaimIsIgnored() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // when - boolean recorded = ledger().markFailed(ID, GrpcClaimToken.FIRST, LATER.plusSeconds(1)); - - // then - assertThat(recorded).isFalse(); - assertThat(ledger().find(ID)) - .get() - .extracting( - GrpcOperationLedgerRecord::state, - GrpcOperationLedgerRecord::claimedAt, - GrpcOperationLedgerRecord::completedAt) - .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, LATER, Optional.empty()); - } - - @Test - @DisplayName("옛 owner 의 실패가 무시되므로 다음 재시도는 진행 중인 새 시도를 다시 claim 하지 못한다") - void aRetryCannotReclaimTheRunningAttemptAfterTheLostOwnerFailed() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - ledger().markFailed(ID, GrpcClaimToken.FIRST, LATER.plusSeconds(1)); - - // when - Optional third = ledger().reclaimFailed(ID, FINGERPRINT, LATER.plusSeconds(2)); - - // then - assertThat(third).isEmpty(); - } - - @Test - @DisplayName("TTL 뒤 넘겨받은 claim 에 옛 owner 가 commit 하면 거부되고 새 시도는 진행 중으로 남는다") - void aCommitByTheOwnerThatLostTheClaimIsRefused() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); - - // when - Throwable refused = - catchThrowable( - () -> ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, LATER.plusSeconds(1))); - - // then - assertThat(refused) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no longer held by attempt 1"); - assertThat(ledger().find(ID)) - .get() - .extracting(GrpcOperationLedgerRecord::state) - .isEqualTo(GrpcOperationLedgerState.IN_PROGRESS); - } - - @Test - @DisplayName("실패 뒤 다시 claim 된 기록에 이전 시도가 commit 하면 거부된다") - void aCommitByTheAttemptBeforeAFailedReclaimIsRefused() { - // given - failedClaim(); - ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); - - // when - Throwable refused = - catchThrowable( - () -> ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(3))); - - // then - assertThat(refused) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no longer held by attempt 1"); - } - - @Test - @DisplayName("한 claim 을 동시에 commit 하면 하나만 성공한다") - void concurrentCommitsOfOneClaimHaveExactlyOneWinner() throws Exception { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - List committed = - concurrently( - () -> { - try { - ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); - return true; - } catch (IllegalStateException refused) { - return false; - } - }); - - // then - assertThat(committed).containsExactlyInAnyOrder(true, false); - } - - @Test - @DisplayName("보존 기간이 지난 COMMITTED·FAILED_TERMINAL 행은 정리된다") - void finishedRecordsCompletedBeforeTheCutoffArePurged() { - // given - committedClaim(ID, NOW); - failedClaim(SECOND_ID, NOW); - - // when - int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 10); - - // then - assertThat(purged).isEqualTo(2); - assertThat(ledger().find(ID)).isEmpty(); - assertThat(ledger().find(SECOND_ID)).isEmpty(); - } - - @Test - @DisplayName("IN_PROGRESS 행은 아무리 오래되어도 정리하지 않는다") - void anInProgressClaimIsNeverPurgedHoweverOld() { - // given - ledger().claim(ID, FINGERPRINT, NOW); - - // when - int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 10); - - // then - assertThat(purged).isZero(); - assertThat(ledger().find(ID)) - .get() - .extracting(GrpcOperationLedgerRecord::state) - .isEqualTo(GrpcOperationLedgerState.IN_PROGRESS); - } - - @Test - @DisplayName("cutoff 이후에 끝난 행은 남긴다") - void finishedRecordsCompletedAtOrAfterTheCutoffAreKept() { - // given - committedClaim(ID, RETENTION_CUTOFF.minusSeconds(1)); - failedClaim(SECOND_ID, RETENTION_CUTOFF.minusSeconds(1)); - - // when - int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 10); - - // then - assertThat(purged).isZero(); - assertThat(ledger().find(ID)).isPresent(); - assertThat(ledger().find(SECOND_ID)).isPresent(); - } - - @Test - @DisplayName("한 번의 정리는 limit 개수까지만 지운다") - void onePurgeDeletesAtMostTheLimit() { - // given - committedClaim(ID, NOW); - committedClaim(SECOND_ID, NOW.plusSeconds(1)); - committedClaim(THIRD_ID, NOW.plusSeconds(2)); - - // when - int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 2); - - // then - assertThat(purged).isEqualTo(2); - assertThat( - Stream.of(ID, SECOND_ID, THIRD_ID) - .filter(identity -> ledger().find(identity).isPresent()) - .count()) - .isEqualTo(1); - } - - @Test - @DisplayName("limit이 양수가 아니면 정리를 거부한다") - void aNonPositivePurgeLimitIsRefused() { - // when - Throwable refused = catchThrowable(() -> ledger().purgeCompletedBefore(RETENTION_CUTOFF, 0)); - - // then - assertThat(refused).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("limit"); - } - - private void failedClaim() { - failedClaim(ID, NOW); - } - - // Claimed at `claimedAt`, finished one second later, so the completion moment is what a purge - // cutoff is compared with. - private void failedClaim(GrpcOperationIdentity identity, Instant claimedAt) { - ledger().claim(identity, FINGERPRINT, claimedAt); - ledger().markFailed(identity, GrpcClaimToken.FIRST, claimedAt.plusSeconds(1)); - } - - private void committedClaim(GrpcOperationIdentity identity, Instant claimedAt) { - ledger().claim(identity, FINGERPRINT, claimedAt); - ledger().markCommitted(identity, GrpcClaimToken.FIRST, OUTCOME, claimedAt.plusSeconds(1)); - } - - private static GrpcOperationIdentity identityWithKeyHash(char hexDigit) { - return new GrpcOperationIdentity( - ID.callerFingerprint(), ID.method(), "sha256:" + String.valueOf(hexDigit).repeat(64)); - } - - /** 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/platforms/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java b/src/platforms/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java deleted file mode 100644 index 7aa38665..00000000 --- a/src/platforms/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java +++ /dev/null @@ -1,205 +0,0 @@ -package dev.caskeleton.grpc.api.ledger; - -import java.time.Instant; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * 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)} and {@code computeIfPresent} - * of its conditional updates, so claim, re-claim, stale takeover, commit, failure and purge are - * atomic here for the same reason they are there. A commit or failure is recorded only for the - * attempt whose {@link GrpcClaimToken} still holds the claim. 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, - GrpcClaimToken claimToken, - String outcomeReference, - Instant now) { - GrpcOperationLedgerRecord committed = - records.computeIfPresent( - identity.storageKey(), - (key, existing) -> { - requireHeldBy(existing, claimToken); - return finish( - existing, GrpcOperationLedgerState.COMMITTED, Optional.of(outcomeReference), now); - }); - if (committed == null) { - throw new IllegalStateException( - "cannot commit operation '" + identity.storageKey() + "': no claim exists"); - } - } - - @Override - public boolean markFailed( - GrpcOperationIdentity identity, GrpcClaimToken claimToken, Instant now) { - AtomicBoolean recorded = new AtomicBoolean(); - records.computeIfPresent( - identity.storageKey(), - (key, existing) -> { - if (existing.state() != GrpcOperationLedgerState.IN_PROGRESS - || !existing.claimToken().equals(claimToken)) { - return existing; - } - recorded.set(true); - return finish(existing, GrpcOperationLedgerState.FAILED_TERMINAL, Optional.empty(), now); - }); - return recorded.get(); - } - - @Override - public Optional reclaimFailed( - GrpcOperationIdentity identity, String requestFingerprint, Instant now) { - GrpcOperationLedgerRecord current = records.get(identity.storageKey()); - if (current == null - || current.state() != GrpcOperationLedgerState.FAILED_TERMINAL - || !current.sameRequestAs(requestFingerprint)) { - return Optional.empty(); - } - return handOver(identity, requestFingerprint, current, now); - } - - @Override - public Optional reclaimStale( - GrpcOperationIdentity identity, - String requestFingerprint, - Instant claimedBefore, - Instant now) { - if (claimedBefore.isAfter(now)) { - throw new IllegalArgumentException( - "a stale-claim cutoff after now would leave the new claim stale as well"); - } - GrpcOperationLedgerRecord current = records.get(identity.storageKey()); - if (current == null - || current.state() != GrpcOperationLedgerState.IN_PROGRESS - || !current.claimedAt().isBefore(claimedBefore) - || !current.sameRequestAs(requestFingerprint)) { - return Optional.empty(); - } - return handOver(identity, requestFingerprint, current, now); - } - - // The conditional replace is the compare-and-set: of two hand-overs of the same record, one wins. - private Optional handOver( - GrpcOperationIdentity identity, - String requestFingerprint, - GrpcOperationLedgerRecord current, - Instant now) { - GrpcClaimToken next = current.claimToken().next(); - return records.replace( - identity.storageKey(), - current, - GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now, next)) - ? Optional.of(next) - : Optional.empty(); - } - - @Override - public int purgeCompletedBefore(Instant completedBefore, int limit) { - if (limit < 1) { - throw new IllegalArgumentException("a purge limit must be positive"); - } - List expired = - records.values().stream() - .filter(record -> record.state().terminal()) - .filter(record -> record.completedAt().orElseThrow().isBefore(completedBefore)) - .sorted(Comparator.comparing(record -> record.completedAt().orElseThrow())) - .limit(limit) - .toList(); - int purged = 0; - for (GrpcOperationLedgerRecord record : expired) { - // Conditional, like the database's re-checked DELETE: a row re-claimed since it was read is - // IN_PROGRESS again and stays. - if (records.remove(record.identity().storageKey(), record)) { - purged++; - } - } - return purged; - } - - @Override - public boolean release(GrpcOperationIdentity identity, GrpcClaimToken claimToken) { - GrpcOperationLedgerRecord existing = records.get(identity.storageKey()); - return existing != null - && existing.state() == GrpcOperationLedgerState.IN_PROGRESS - && existing.claimToken().equals(claimToken) - && records.remove(identity.storageKey(), existing); - } - - // An attempt that lost the claim must not commit beside the attempt that holds it; checked - // before the state, so a lost owner hears that it lost rather than that the row finished. - private static void requireHeldBy(GrpcOperationLedgerRecord existing, GrpcClaimToken claimToken) { - if (!existing.claimToken().equals(claimToken)) { - throw new IllegalStateException( - "operation '" - + existing.identity().storageKey() - + "' is no longer held by attempt " - + claimToken.attempt() - + "; attempt " - + existing.claimToken().attempt() - + " holds it"); - } - } - - // 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), - existing.claimToken()); - } -} diff --git a/src/platforms/grpc/grpc-observability/build.gradle b/src/platforms/grpc/grpc-observability/build.gradle deleted file mode 100644 index f6ed15c0..00000000 --- a/src/platforms/grpc/grpc-observability/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Bounded observability: logical RPC vs physical attempt vs stream lifecycle, with a cardinality -// policy that refuses payload, raw metadata and any actor/tenant/object/stream/idempotency -// identifier as a tag. -dependencies { - api project(':grpc:grpc-core-api') - - // api: the observation convention's public signatures name Micrometer types, so wiring it - // requires naming them. - api 'io.micrometer:micrometer-core' -} diff --git a/src/platforms/grpc/grpc-observability/gradle.lockfile b/src/platforms/grpc/grpc-observability/gradle.lockfile deleted file mode 100644 index dcab1d05..00000000 --- a/src/platforms/grpc/grpc-observability/gradle.lockfile +++ /dev/null @@ -1,87 +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.50.0=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.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.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.8=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.6.1=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.20=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.20=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicy.java b/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicy.java deleted file mode 100644 index a48db400..00000000 --- a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicy.java +++ /dev/null @@ -1,123 +0,0 @@ -package dev.caskeleton.grpc.observability; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * Which tags may go on a metric, and which may never. - * - *

An allowlist, because the failure is not a bad tag — it is an unbounded one. A tag whose value - * space grows with traffic multiplies every time series by that space: one tenant id turns a - * hundred series into a hundred thousand, and the metric backend either drops the data or bills for - * it. By the time anyone notices, the dashboards built on those metrics are already gone. - * - *

The forbidden list is separate from "not on the allowlist" on purpose. Everything unlisted is - * refused anyway; naming the dangerous ones gives the refusal a message that says why rather than - * just that. - */ -public final class GrpcMetricCardinalityPolicy { - - /** The tags a bounded metric may carry. */ - private static final Set ALLOWED_TAGS = - Set.of( - "grpc.service", - "grpc.method", - "grpc.rpc_type", - "grpc.status", - "grpc.channel_profile", - "grpc.completion_outcome", - "grpc.retry_bucket", - "grpc.stream_termination_reason"); - - /** Tags whose value space grows with traffic, or which carry content. */ - private static final Set FORBIDDEN_TAGS = - Set.of( - "grpc.actor_id", - "grpc.tenant_id", - "grpc.object_id", - "grpc.stream_id", - "grpc.idempotency_key", - "grpc.request", - "grpc.response", - "grpc.metadata", - "grpc.authorization", - "grpc.error_detail", - "grpc.trace_id"); - - private static final Pattern UNBOUNDED_VALUE = - Pattern.compile( - "(?i).*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|sha256:|bearer ).*"); - - /** The retry buckets, so attempt counts do not become a tag value per attempt. */ - private static final List RETRY_BUCKETS = List.of("0", "1", "2", "3+"); - - private GrpcMetricCardinalityPolicy() {} - - /** The allowed tag keys. */ - public static Set allowedTags() { - return ALLOWED_TAGS; - } - - /** The explicitly forbidden tag keys. */ - public static Set forbiddenTags() { - return FORBIDDEN_TAGS; - } - - /** - * Every problem with a proposed tag set. - * - * @return an empty list when the tags are bounded and none carries content - */ - public static List violations(Map tags) { - if (tags == null) { - throw new IllegalArgumentException("a tag set is required"); - } - List violations = new ArrayList<>(); - tags.forEach( - (key, value) -> { - if (FORBIDDEN_TAGS.contains(key)) { - violations.add( - "tag '" - + key - + "' is forbidden: its value space grows with traffic, so every series is " - + "multiplied by it"); - return; - } - if (!ALLOWED_TAGS.contains(key)) { - violations.add( - "tag '" - + key - + "' is not on the bounded allowlist " - + ALLOWED_TAGS.stream().sorted().toList()); - return; - } - if (value != null && UNBOUNDED_VALUE.matcher(value).matches()) { - violations.add( - "tag '" + key + "' carries a value that looks like an identifier or a credential"); - } - }); - return List.copyOf(violations); - } - - /** - * The bucket an attempt number belongs in. - * - *

Bucketed rather than tagged directly, because an attempt count is unbounded in principle and - * the distinction anyone acts on is first attempt, one retry, several. - */ - public static String retryBucket(int attempt) { - if (attempt < 1) { - throw new IllegalArgumentException("attempt is 1-based"); - } - int retries = attempt - 1; - return retries >= 3 ? "3+" : RETRY_BUCKETS.get(retries); - } - - /** Every retry bucket, so a dashboard can enumerate them. */ - public static List retryBuckets() { - return RETRY_BUCKETS; - } -} diff --git a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcObservationConvention.java b/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcObservationConvention.java deleted file mode 100644 index 9dd6d3b6..00000000 --- a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcObservationConvention.java +++ /dev/null @@ -1,99 +0,0 @@ -package dev.caskeleton.grpc.observability; - -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Tags; -import io.micrometer.core.instrument.Timer; -import java.util.List; -import java.util.Map; - -/** - * Registers gRPC measurements against Micrometer under one naming and tagging convention. - * - *

Every registration goes through {@link GrpcMetricCardinalityPolicy} first, and a violation - * throws rather than being dropped. Dropping would be gentler at runtime and worse in practice: the - * unbounded tag would keep being written by whatever added it, and the first symptom would be the - * metric backend refusing the series in production. - * - *

Attempts are recorded as counter increments under the logical call's tags rather than as their - * own timed calls, which is what keeps a retried-and-succeeded call from reading as two failures - * and a success. - */ -public final class GrpcObservationConvention { - - /** Timer for a logical RPC, retries included. */ - public static final String RPC_DURATION = "grpc.rpc.duration"; - - /** Counter of physical attempts, including the first. */ - public static final String RPC_ATTEMPTS = "grpc.rpc.attempts"; - - /** Counter of calls whose business outcome could not be determined. */ - public static final String COMPLETION_UNKNOWN = "grpc.rpc.completion_unknown"; - - /** Timer for how long a call waited for a ready channel. */ - public static final String QUEUE_WAIT = "grpc.rpc.queue_wait"; - - /** Timer for a stream's whole lifetime. */ - public static final String STREAM_LIFETIME = "grpc.stream.lifetime"; - - /** Counter of messages a stream sent. */ - public static final String STREAM_MESSAGES = "grpc.stream.messages"; - - /** Counter of times a stream writer paused waiting for the transport. */ - public static final String STREAM_FLOW_CONTROL_STALLS = "grpc.stream.flow_control_stalls"; - - private final MeterRegistry registry; - - /** Binds the convention to a registry. */ - public GrpcObservationConvention(MeterRegistry registry) { - if (registry == null) { - throw new IllegalArgumentException("an observation convention needs a meter registry"); - } - this.registry = registry; - } - - /** Records one logical RPC and its attempts. */ - public void record(GrpcRpcObservation observation) { - if (observation == null) { - throw new IllegalArgumentException("an observation is required"); - } - Tags tags = boundedTags(observation.tags()); - Timer.builder(RPC_DURATION).tags(tags).register(registry).record(observation.duration()); - registry.counter(RPC_ATTEMPTS, tags).increment(observation.attempts()); - if (observation.completionOutcome().requiresReconciliation()) { - registry.counter(COMPLETION_UNKNOWN, tags).increment(); - } - if (!observation.queueWaitTime().isZero()) { - Timer.builder(QUEUE_WAIT).tags(tags).register(registry).record(observation.queueWaitTime()); - } - } - - /** Records one stream's lifetime. */ - public void record(GrpcStreamObservation observation) { - if (observation == null) { - throw new IllegalArgumentException("an observation is required"); - } - Tags tags = boundedTags(observation.tags()); - Timer.builder(STREAM_LIFETIME).tags(tags).register(registry).record(observation.lifetime()); - // Explicit widening: a long counter delta is a double to Micrometer, and leaving the - // conversion implicit is a precision question the compiler is right to ask about. - registry.counter(STREAM_MESSAGES, tags).increment((double) observation.messagesSent()); - registry - .counter(STREAM_FLOW_CONTROL_STALLS, tags) - .increment((double) observation.flowControlStalls()); - } - - /** - * Converts a tag map after checking it. - * - * @throws IllegalArgumentException naming every unbounded or content-bearing tag - */ - public static Tags boundedTags(Map tags) { - List violations = GrpcMetricCardinalityPolicy.violations(tags); - if (!violations.isEmpty()) { - throw new IllegalArgumentException( - "refusing to register a metric with unbounded or content-bearing tags: " + violations); - } - return Tags.of(tags.entrySet().stream().map(e -> Tag.of(e.getKey(), e.getValue())).toList()); - } -} diff --git a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcRpcObservation.java b/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcRpcObservation.java deleted file mode 100644 index d305c2e3..00000000 --- a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcRpcObservation.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.grpc.observability; - -import dev.caskeleton.grpc.api.error.GrpcCompletionOutcome; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.GrpcStatusCode; -import dev.caskeleton.grpc.core.RpcType; -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; - -/** - * One RPC, measured at the level a caller cares about. - * - *

The logical call, not the attempt. A retried call is one observation with a retry bucket, and - * three attempt events beneath it; recording three separate calls instead makes the success rate - * read as 33% when the caller in fact got its answer. The two levels answer different questions and - * keeping them apart is what makes either usable. - * - *

{@code deadlineRemaining} and {@code queueWaitTime} are recorded because they are the two - * numbers that explain a latency change without being latency. A p99 that doubles during a rollout - * is a different incident depending on whether callers were queueing. - */ -public record GrpcRpcObservation( - GrpcMethodName method, - RpcType rpcType, - GrpcStatusCode status, - GrpcCompletionOutcome completionOutcome, - String channelProfile, - int attempts, - Duration duration, - Duration deadlineRemaining, - Duration queueWaitTime) { - - /** Requires the identity and non-negative measurements. */ - public GrpcRpcObservation { - if (method == null || rpcType == null || status == null || completionOutcome == null) { - throw new IllegalArgumentException("an observation identifies the call and its outcome"); - } - if (attempts < 1) { - throw new IllegalArgumentException("an observed call has at least one attempt"); - } - if (duration == null || duration.isNegative()) { - throw new IllegalArgumentException("duration must be present and non-negative"); - } - if (deadlineRemaining == null || queueWaitTime == null || queueWaitTime.isNegative()) { - throw new IllegalArgumentException("deadline and queue measurements must be present"); - } - } - - /** - * The bounded tag set for this observation. - * - *

Built here rather than at each meter registration, so there is one answer to what a gRPC - * metric is tagged with and {@link GrpcMetricCardinalityPolicy} has one thing to check. - */ - public Map tags() { - Map tags = new LinkedHashMap<>(); - tags.put("grpc.service", method.service().value()); - tags.put("grpc.method", method.method()); - tags.put("grpc.rpc_type", rpcType.name()); - tags.put("grpc.status", status.name()); - tags.put("grpc.completion_outcome", completionOutcome.name()); - tags.put("grpc.channel_profile", channelProfile == null ? "server" : channelProfile); - tags.put("grpc.retry_bucket", GrpcMetricCardinalityPolicy.retryBucket(attempts)); - return Map.copyOf(tags); - } - - /** Whether this call needed more than one attempt. */ - public boolean retried() { - return attempts > 1; - } - - /** How much of the deadline was left when the call ended, if any. */ - public Optional unusedDeadline() { - return deadlineRemaining.isNegative() ? Optional.empty() : Optional.of(deadlineRemaining); - } -} diff --git a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcStreamObservation.java b/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcStreamObservation.java deleted file mode 100644 index c5628d79..00000000 --- a/src/platforms/grpc/grpc-observability/src/main/java/dev/caskeleton/grpc/observability/GrpcStreamObservation.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.grpc.observability; - -import dev.caskeleton.grpc.core.GrpcMethodName; -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * A stream's lifetime, measured as a lifetime rather than as a call. - * - *

Duration percentiles are meaningless here — a healthy subscription lasts an hour and an - * unhealthy one lasts an hour — so what is recorded instead is what actually distinguishes them: - * how many messages moved, how often the writer stalled waiting for the transport, and how it - * ended. A rise in flow-control stalls is a consumer falling behind, which is invisible in a - * latency metric. - */ -public record GrpcStreamObservation( - GrpcMethodName method, - String channelProfile, - String terminationReason, - long messagesSent, - long flowControlStalls, - long queueHighWatermark, - Duration lifetime) { - - /** Requires the identity and non-negative counters. */ - public GrpcStreamObservation { - if (method == null || terminationReason == null || terminationReason.isBlank()) { - throw new IllegalArgumentException("a stream observation names its method and how it ended"); - } - if (messagesSent < 0 || flowControlStalls < 0 || queueHighWatermark < 0) { - throw new IllegalArgumentException("stream counters must not be negative"); - } - if (lifetime == null || lifetime.isNegative()) { - throw new IllegalArgumentException("a stream observation records how long it lived"); - } - } - - /** The bounded tag set. The stream id is deliberately absent. */ - public Map tags() { - Map tags = new LinkedHashMap<>(); - tags.put("grpc.service", method.service().value()); - tags.put("grpc.method", method.method()); - tags.put("grpc.rpc_type", "SERVER_STREAMING"); - tags.put("grpc.channel_profile", channelProfile == null ? "server" : channelProfile); - tags.put("grpc.stream_termination_reason", terminationReason); - return Map.copyOf(tags); - } - - /** Whether the writer spent time blocked on a consumer that could not keep up. */ - public boolean consumerFellBehind() { - return flowControlStalls > 0; - } -} diff --git a/src/platforms/grpc/grpc-observability/src/test/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicyTest.java b/src/platforms/grpc/grpc-observability/src/test/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicyTest.java deleted file mode 100644 index 6cb5ebd2..00000000 --- a/src/platforms/grpc/grpc-observability/src/test/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicyTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package dev.caskeleton.grpc.observability; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.api.error.GrpcCompletionOutcome; -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.GrpcStatusCode; -import dev.caskeleton.grpc.core.RpcType; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcMetricCardinalityPolicyTest { - - private static final GrpcMethodName GET = - GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - - private static GrpcRpcObservation observation(int attempts, GrpcCompletionOutcome outcome) { - return new GrpcRpcObservation( - GET, - RpcType.UNARY, - GrpcStatusCode.OK, - outcome, - "documents-read", - attempts, - Duration.ofMillis(120), - Duration.ofMillis(880), - Duration.ZERO); - } - - @Test - @DisplayName("only the bounded tags are allowed") - void onlyBoundedTagsAreAllowed() { - assertThat(GrpcMetricCardinalityPolicy.allowedTags()) - .containsExactlyInAnyOrder( - "grpc.service", - "grpc.method", - "grpc.rpc_type", - "grpc.status", - "grpc.channel_profile", - "grpc.completion_outcome", - "grpc.retry_bucket", - "grpc.stream_termination_reason"); - assertThat( - GrpcMetricCardinalityPolicy.violations( - observation(1, GrpcCompletionOutcome.COMPLETED).tags())) - .isEmpty(); - } - - @Test - @DisplayName("actor, tenant, object, stream and idempotency identifiers are refused") - void unboundedIdentifierTagsAreRefused() { - Map tags = new LinkedHashMap<>(); - tags.put("grpc.tenant_id", "tenant-1"); - tags.put("grpc.actor_id", "actor-1"); - tags.put("grpc.stream_id", "stream-1"); - tags.put("grpc.idempotency_key", "order-1"); - tags.put("grpc.object_id", "document-1"); - - assertThat(GrpcMetricCardinalityPolicy.violations(tags)) - .hasSize(5) - .allSatisfy( - violation -> assertThat(violation).contains("every series is multiplied by it")); - } - - @Test - @DisplayName("payload, metadata and raw error detail are refused") - void contentBearingTagsAreRefused() { - Map tags = new LinkedHashMap<>(); - tags.put("grpc.request", "{...}"); - tags.put("grpc.metadata", "authorization=Bearer x"); - tags.put("grpc.error_detail", "SQLState 23505"); - - assertThat(GrpcMetricCardinalityPolicy.violations(tags)).hasSize(3); - } - - @Test - @DisplayName("an allowed tag carrying an identifier-shaped value is still refused") - void anIdentifierShapedValueIsRefused() { - assertThat( - GrpcMetricCardinalityPolicy.violations( - Map.of("grpc.channel_profile", "8f14e45f-ceea-467a-9a0e-4e2c9a1b3d55"))) - .singleElement() - .satisfies(violation -> assertThat(violation).contains("looks like an identifier")); - assertThat(GrpcMetricCardinalityPolicy.violations(Map.of("grpc.status", "Bearer eyJhbGci"))) - .isNotEmpty(); - } - - @Test - @DisplayName("an unlisted tag is refused with the allowlist in the message") - void unlistedTagsAreRefused() { - assertThat(GrpcMetricCardinalityPolicy.violations(Map.of("grpc.pod_name", "documents-7f9"))) - .singleElement() - .satisfies(violation -> assertThat(violation).contains("bounded allowlist")); - } - - @Test - @DisplayName("attempts are bucketed rather than tagged one per value") - void attemptsAreBucketed() { - assertThat(GrpcMetricCardinalityPolicy.retryBucket(1)).isEqualTo("0"); - assertThat(GrpcMetricCardinalityPolicy.retryBucket(2)).isEqualTo("1"); - assertThat(GrpcMetricCardinalityPolicy.retryBucket(4)).isEqualTo("3+"); - assertThat(GrpcMetricCardinalityPolicy.retryBucket(99)).isEqualTo("3+"); - assertThat(GrpcMetricCardinalityPolicy.retryBuckets()).containsExactly("0", "1", "2", "3+"); - assertThatThrownBy(() -> GrpcMetricCardinalityPolicy.retryBucket(0)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a retried call is one observation with a bucket, not three calls") - void aRetriedCallIsOneObservation() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - GrpcObservationConvention convention = new GrpcObservationConvention(registry); - - convention.record(observation(3, GrpcCompletionOutcome.COMPLETED)); - - assertThat(registry.get(GrpcObservationConvention.RPC_DURATION).timer().count()).isEqualTo(1L); - assertThat(registry.get(GrpcObservationConvention.RPC_ATTEMPTS).counter().count()) - .isEqualTo(3.0d); - assertThat( - registry - .get(GrpcObservationConvention.RPC_DURATION) - .timer() - .getId() - .getTag("grpc.retry_bucket")) - .isEqualTo("2"); - } - - @Test - @DisplayName("a completion-unknown call is counted separately") - void completionUnknownIsCountedSeparately() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - GrpcObservationConvention convention = new GrpcObservationConvention(registry); - - convention.record(observation(1, GrpcCompletionOutcome.COMPLETION_UNKNOWN)); - - assertThat(registry.get(GrpcObservationConvention.COMPLETION_UNKNOWN).counter().count()) - .isEqualTo(1.0d); - } - - @Test - @DisplayName("a stream is measured by messages and stalls, and never tagged with its id") - void streamsAreMeasuredByMessagesAndStalls() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - GrpcObservationConvention convention = new GrpcObservationConvention(registry); - GrpcStreamObservation observation = - new GrpcStreamObservation( - GET, "documents-stream", "SLOW_CONSUMER", 1200L, 7L, 250L, Duration.ofMinutes(12)); - - convention.record(observation); - - assertThat(observation.tags()).doesNotContainKey("grpc.stream_id"); - assertThat(observation.consumerFellBehind()).isTrue(); - assertThat(registry.get(GrpcObservationConvention.STREAM_MESSAGES).counter().count()) - .isEqualTo(1200.0d); - assertThat(registry.get(GrpcObservationConvention.STREAM_FLOW_CONTROL_STALLS).counter().count()) - .isEqualTo(7.0d); - } - - @Test - @DisplayName("registering a metric with an unbounded tag throws rather than dropping it") - void anUnboundedTagThrowsRatherThanBeingDropped() { - assertThatThrownBy( - () -> GrpcObservationConvention.boundedTags(Map.of("grpc.tenant_id", "tenant-1"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("refusing to register"); - } -} diff --git a/src/platforms/grpc/grpc-operation-ledger-jpa/build.gradle b/src/platforms/grpc/grpc-operation-ledger-jpa/build.gradle deleted file mode 100644 index 6a83f775..00000000 --- a/src/platforms/grpc/grpc-operation-ledger-jpa/build.gradle +++ /dev/null @@ -1,76 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -testing { - suites { - integrationTest(JvmTestSuite) { - dependencies { - implementation project() - } - } - } -} -configurations { - integrationTestImplementation.extendsFrom testImplementation - integrationTestRuntimeOnly.extendsFrom testRuntimeOnly -} - -// One definition of a versioned migration file and of Flyway's order for both builds (re-review -// README 12, r6-b; r9), and one concurrent index check (round 7, RR7-03-01). This build cannot -// depend on persistence-jpa's testkit, so the files the ledger lanes need from it, all JDK only — -// VersionedMigrationFiles, and ConcurrentIndexMigrationInspector with the MigrationResource it -// takes — are copied from there into this lane's sources at build time instead of being kept here -// as second copies that could drift. -// Rejected: that testkit directory as a source root of this lane (Spotless refuses a target outside -// this project's directory, and the include filter would cover this lane's own sources too), a -// dependency on the main build (it would pull the whole main build into this one), and a test that -// compares two copies (two definitions stay, and the test would have to parse Java source text). -def sharedMigrationFileSources = tasks.register('sharedMigrationFileSources', Sync) { - from(file('../../../adapter/outbound/persistence-jpa/src/testFixtures/java')) { - include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java' - include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java' - include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java' - } - into(layout.buildDirectory.dir('generated/sources/sharedMigrationFiles/java')) -} -sourceSets.integrationTest.java.srcDir(sharedMigrationFileSources) -// The copy is not this build's to format: Spotless here would name the generated file, and its -// spotlessApply would rewrite only that copy, which the next Sync puts back (re-review 2026-11-03 -// round 6, RR6-03-04). The main build's persistence-jpa spotlessCheck formats the original. -spotless { - java { - targetExclude('build/generated/sources/sharedMigrationFiles/**') - } -} - -// Durable mutation idempotency: the operation ledger entity, its state machine, the vendor-neutral -// repository port and the Spring Data JPA binding, plus the migration that owns the unique -// constraint the whole contract rests on. -// -// The claim algorithm is PostgreSQL-specific by design (INSERT ... ON CONFLICT DO NOTHING), so its -// atomicity is certified against a real PostgreSQL instead of a hand-written repository fake. -dependencies { - api project(':grpc:grpc-core-api') - - // api: the ledger entity is a public JPA type and the repository interface is a public Spring - // Data type, so both vendor APIs appear in this module's public signatures. - api 'jakarta.persistence:jakarta.persistence-api' - api 'org.springframework.data:spring-data-jpa' - - 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 { - lane('integrationTest') { - integration() - sourceSet = 'integrationTest' - description = 'Certifies atomic gRPC idempotency claims against real PostgreSQL.' - } -} diff --git a/src/platforms/grpc/grpc-operation-ledger-jpa/gradle.lockfile b/src/platforms/grpc/grpc-operation-ledger-jpa/gradle.lockfile deleted file mode 100644 index 11c777e4..00000000 --- a/src/platforms/grpc/grpc-operation-ledger-jpa/gradle.lockfile +++ /dev/null @@ -1,127 +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.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 -com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,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,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,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,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.50.0=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -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 -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,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -info.picocli:picocli:4.7.7=checkstyle -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.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.8=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 -net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -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-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,testCompileClasspath -org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.checkerframework:checker-qual:3.55.1=integrationTestRuntimeClasspath -org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle -org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle -org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle -org.codehaus.plexus:plexus-utils:3.6.1=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.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.25.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 -org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath -org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit:junit-bom:6.1.0=spotbugs -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,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,testAnnotationProcessor -org.postgresql:postgresql:42.7.14=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.reflections:reflections:0.10.2=checkstyle -org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.slf4j:slf4j-api:2.0.20=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.20=checkstyle -org.springframework.data:spring-data-commons:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.data:spring-data-jpa:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-jdbc:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-orm:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.10=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.testcontainers:testcontainers-database-commons:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers-jdbc:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers-postgresql: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/platforms/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java b/src/platforms/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java deleted file mode 100644 index 9ff4829b..00000000 --- a/src/platforms/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java +++ /dev/null @@ -1,347 +0,0 @@ -package dev.caskeleton.grpc.ledger; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.junit.jupiter.params.provider.Arguments.arguments; - -import dev.caskeleton.adapter.outbound.persistence.testkit.migration.ConcurrentIndexMigrationInspector; -import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationResource; -import java.io.IOException; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.stream.Stream; -import org.junit.jupiter.api.DisplayName; -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.postgresql.ds.PGSimpleDataSource; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.postgresql.PostgreSQLContainer; - -/** - * The ledger migrations after V001 lock a table already in use and give up within their bound - * instead of stopping it (re-review 2026-11-03 round 2, RR-02-09: the rule V21 follows). - * - *

A transaction that has written the ledger stays open for fifteen seconds — a claim in flight, - * an operator's {@code BEGIN}. A write is the holder both migrations wait for: V003's ALTER TABLE - * would wait for a read too, V002's plain CREATE INDEX only for a write. The migration runs in one - * transaction, which is how Flyway runs the files this tree has: a {@code SET LOCAL lock_timeout} - * and statements that run in a transaction. Unbounded it waits until the writer leaves, with every - * claim queued behind it, and then applies; bounded it fails with {@code lock_not_available} first - * and its rollback leaves the ledger as it was. - * - *

A file Flyway runs outside a transaction — one holding {@code CREATE INDEX CONCURRENTLY} or - * another statement on Flyway's list, or with {@code executeInTransaction=false} beside it — is not - * one this test can judge: run here in a transaction, PostgreSQL refuses it ({@code 25001}), and no - * {@code SET LOCAL} would bound it in a deploy anyway. The one such file the ledger may have is a - * concurrent index build, and it goes in {@link #RUN_OUTSIDE_A_TRANSACTION} with the reason it - * needs to: the lock-wait case leaves it out, and {@code - * everyMigrationListedAsRunningOutsideATransactionIsOneConcurrentIndexBuildThatSaysSo} holds it to - * the guide instead — a concurrent index statement, alone in its file, with {@code - * executeInTransaction=false} beside it ({@code docs/jpa/migration-guide.md}, "Concurrent index - * builds"). The list takes nothing else: a {@code VACUUM FULL} or another locking statement that - * cannot run in a transaction does not belong in a migration at all ("Bound the lock wait"). The - * migrations before the one under test are applied one file at a time ({@link - * GrpcOperationLedgerMigrations#before(String)}), so a listed file is no obstacle to a later one. - * Re-review 2026-11-03 round 6, RR6-03-05; round 7, RR7-03-01: the message pointed at a list this - * test did not have. - * - *

Every migration after V001 is held to this, read from the tree itself ({@link - * GrpcOperationLedgerMigrations#inOrder()}), so a V004 is checked without anyone naming it here. - * This is the ledger tree's lock-wait rule: the optional build cannot depend on the persistence-jpa - * testkit whose text check the other trees run (it compiles only the testkit's file list, {@code - * VersionedMigrationFiles}), and a copy of that check would drift (re-review 2026-11-03 round 3, - * RR3-02-04). A later migration that does not touch the ledger at all fails here too, on purpose: - * say so in this test rather than let the rule pass it unseen. - */ -@Testcontainers(disabledWithoutDocker = true) -class GrpcOperationLedgerMigrationLockWaitIT { - - private static final String LOCK_NOT_AVAILABLE = "55P03"; - private static final String ACTIVE_SQL_TRANSACTION = "25001"; - private static final Duration WRITER_STAYS = Duration.ofSeconds(15); - private static final Duration GIVES_UP_WITHIN = Duration.ofSeconds(10); - - @SuppressWarnings("resource") - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) - .withDatabaseName("grpc") - .withUsername("grpc") - .withPassword("grpc"); - - /** - * The ledger migrations Flyway runs outside a transaction, by file name, each with why it has to: - * a concurrent index build that would stop the ledger's writes if it were built in a transaction. - * Empty while the tree has none. - */ - static final Map RUN_OUTSIDE_A_TRANSACTION = Map.of(); - - /** The file name the list check's fixture cases list. */ - private static final String LISTED = "V004__ledger_index.sql"; - - /** A concurrent index build alone, as the guide asks such a file to be. */ - private static final String CONCURRENT_BUILD = - "CREATE INDEX CONCURRENTLY ix_ledger_note ON grpc_operation_ledger (note);\n"; - - /** Every ledger migration after V001, the one that creates the ledger, that runs in one. */ - static Stream migrationsAfterTheFirst() throws IOException { - return GrpcOperationLedgerMigrations.inOrder().stream() - .skip(1) - .filter(migration -> !RUN_OUTSIDE_A_TRANSACTION.containsKey(migration)); - } - - @ParameterizedTest - @MethodSource("migrationsAfterTheFirst") - @DisplayName("ledger에 쓴 트랜잭션이 열려 있으면 ledger를 잠그는 마이그레이션은 상한 안에 실패하고 아무것도 바꾸지 않는다") - void aLedgerMigrationGivesUpOnAnOpenWriterAndChangesNothing(String migration) throws Exception { - PGSimpleDataSource dataSource = dataSource(); - try (Connection setup = dataSource.getConnection(); - Statement statement = setup.createStatement()) { - // given - statement.execute("DROP TABLE IF EXISTS grpc_operation_ledger"); - for (String script : GrpcOperationLedgerMigrations.before(migration)) { - statement.execute(script); - } - String schemaBefore = schema(statement); - - // when - Attempt attempt = - whileAWriterHolds(dataSource, GrpcOperationLedgerMigrations.named(migration)); - - // then - assertThat( - List.of( - String.valueOf(attempt.sqlState()), - attempt.took().compareTo(GIVES_UP_WITHIN) < 0, - schema(statement))) - .as( - "%s must put SET LOCAL lock_timeout = '5s'; before it locks the ledger" - + " (docs/jpa/migration-guide.md, \"Bound the lock wait\")%s", - migration, - ACTIVE_SQL_TRANSACTION.equals(attempt.sqlState()) - ? ". PostgreSQL refused it inside a transaction (25001): Flyway runs such a file" - + " outside one, where SET LOCAL bounds nothing, so it is no case for this" - + " test. If it is a concurrent index build, keep it alone in its migration" - + " with executeInTransaction=false beside it and add it, with the reason, to" - + " RUN_OUTSIDE_A_TRANSACTION in this test (\"Concurrent index builds\");" - + " anything else that cannot run in a transaction does not belong in a" - + " migration (\"Bound the lock wait\")" - : "") - .containsExactly(LOCK_NOT_AVAILABLE, true, schemaBefore); - } - } - - @Test - @DisplayName( - "트랜잭션 밖에서 도는 예외 목록의 ledger 마이그레이션은 트리에 있고, 동시 인덱스 문장 하나뿐이며, executeInTransaction=false를 적었다") - void everyMigrationListedAsRunningOutsideATransactionIsOneConcurrentIndexBuildThatSaysSo() - throws IOException { - // given - Map tree = new LinkedHashMap<>(); - for (String migration : GrpcOperationLedgerMigrations.inOrder()) { - tree.put( - migration, - new LedgerMigration( - GrpcOperationLedgerMigrations.named(migration), - GrpcOperationLedgerMigrations.executeInTransaction(migration))); - } - - // when - List refused = refusalsOf(RUN_OUTSIDE_A_TRANSACTION.keySet(), tree); - - // then - assertThat(refused).isEmpty(); - } - - @ParameterizedTest - @MethodSource("listedFilesTheGuideDoesNotAllow") - @DisplayName( - "예외 목록 검사는 트리에 없는 파일, 동시 인덱스 문장이 없는 파일, executeInTransaction=false가 없는 파일, 다른 문장과 섞인 파일을 이유와 함께 거부한다") - void theListCheckRefusesAFileTheGuideDoesNotAllow( - String listed, Map tree, String reason) { - // when - List refused = refusalsOf(List.of(listed), tree); - - // then - assertThat(refused).singleElement().asString().contains(listed).contains(reason); - } - - @Test - @DisplayName("예외 목록 검사는 executeInTransaction=false를 곁에 둔, 동시 인덱스 문장 하나뿐인 파일을 받는다") - void theListCheckAcceptsAConcurrentIndexBuildAloneThatSaysSo() { - // given - Map tree = - Map.of(LISTED, new LedgerMigration(CONCURRENT_BUILD, false)); - - // when - List refused = refusalsOf(List.of(LISTED), tree); - - // then - assertThat(refused).isEmpty(); - } - - /** One listed file for each way the guide's rule can be broken, and the reason it is refused. */ - static Stream listedFilesTheGuideDoesNotAllow() { - return Stream.of( - arguments(LISTED, Map.of(), "is not a migration in the ledger tree"), - arguments( - LISTED, - Map.of( - LISTED, - new LedgerMigration( - "ALTER TABLE grpc_operation_ledger ADD COLUMN note TEXT;\n", false)), - "holds no concurrent index statement"), - arguments( - LISTED, - Map.of(LISTED, new LedgerMigration(CONCURRENT_BUILD, true)), - "must set executeInTransaction=false"), - arguments( - LISTED, - Map.of( - LISTED, - new LedgerMigration("SET LOCAL lock_timeout = '5s';\n" + CONCURRENT_BUILD, false)), - "mixes a concurrent index statement with other statements")); - } - - /** - * Why each migration listed as running outside a transaction may not: one reason per file - * refused, none when every listed file is in the tree and is a concurrent index statement alone - * in its file with {@code executeInTransaction=false} beside it ("Concurrent index builds"). The - * list test runs it over {@link #RUN_OUTSIDE_A_TRANSACTION} and the tree, and the fixture cases - * hold it to every refusal while that list is empty (re-review 2026-11-03 round 8, RR8-03-04: its - * loop never ran, so a broken check passed). - * - * @param listed the file names listed - * @param tree every migration in the tree, by file name - * @return the reasons, in the order the files are listed - */ - static List refusalsOf(Collection listed, Map tree) { - ConcurrentIndexMigrationInspector inspector = new ConcurrentIndexMigrationInspector(); - List refused = new ArrayList<>(); - for (String migration : listed) { - LedgerMigration file = tree.get(migration); - if (file == null) { - refused.add(migration + " is not a migration in the ledger tree"); - continue; - } - MigrationResource resource = new MigrationResource(migration, file.sql()); - if (!inspector.containsConcurrentIndexStatement(resource.sql())) { - refused.add( - migration - + " holds no concurrent index statement; only a concurrent index build may run" - + " outside a transaction"); - continue; - } - Throwable thrown = - catchThrowable( - () -> { - inspector.validate(resource, file.executeInTransaction()); - inspector.requireIsolatedStatement(resource); - }); - if (thrown != null) { - refused.add(thrown.getMessage()); - } - } - return refused; - } - - /** Runs the migration in one transaction while another one holds a write to the ledger. */ - private static Attempt whileAWriterHolds(PGSimpleDataSource dataSource, String migration) - throws SQLException { - try (Connection writer = dataSource.getConnection(); - Connection migrator = dataSource.getConnection()) { - writer.setAutoCommit(false); - try (Statement write = writer.createStatement()) { - write.execute("LOCK TABLE grpc_operation_ledger IN ROW EXCLUSIVE MODE"); - } - ScheduledExecutorService release = Executors.newSingleThreadScheduledExecutor(); - ScheduledFuture released = - release.schedule( - () -> { - writer.rollback(); - return null; - }, - WRITER_STAYS.toSeconds(), - TimeUnit.SECONDS); - try { - migrator.setAutoCommit(false); - long started = System.nanoTime(); - Throwable thrown = - catchThrowable( - () -> { - try (Statement statement = migrator.createStatement()) { - statement.execute(migration); - } - migrator.commit(); - }); - Duration took = Duration.ofNanos(System.nanoTime() - started); - migrator.rollback(); - return new Attempt(thrown, took); - } finally { - released.cancel(true); - release.shutdownNow(); - } - } - } - - /** The ledger's columns, indexes and constraints, enough to see whether a migration landed. */ - private static String schema(Statement statement) throws SQLException { - try (ResultSet row = - statement.executeQuery( - "SELECT (SELECT string_agg(column_name, ',' ORDER BY column_name)" - + " FROM information_schema.columns" - + " WHERE table_name = 'grpc_operation_ledger')" - + " || '|' || (SELECT string_agg(indexname, ',' ORDER BY indexname)" - + " FROM pg_indexes WHERE tablename = 'grpc_operation_ledger')" - + " || '|' || (SELECT string_agg(conname, ',' ORDER BY conname) FROM pg_constraint" - + " WHERE conrelid = 'grpc_operation_ledger'::regclass)")) { - row.next(); - return row.getString(1); - } - } - - private static PGSimpleDataSource dataSource() { - PGSimpleDataSource dataSource = new PGSimpleDataSource(); - dataSource.setUrl(POSTGRES.getJdbcUrl()); - dataSource.setUser(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); - return dataSource; - } - - /** - * A ledger migration as the list check reads it. - * - * @param sql the script - * @param executeInTransaction whether Flyway runs it in a transaction, as {@link - * GrpcOperationLedgerMigrations#executeInTransaction} reads it from the file beside it - */ - record LedgerMigration(String sql, boolean executeInTransaction) {} - - /** What the migration did while the writer held the ledger. */ - private record Attempt(Throwable thrown, Duration took) { - - String sqlState() { - for (Throwable cause = thrown; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql) { - return sql.getSQLState(); - } - } - return null; - } - } -} diff --git a/src/platforms/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java b/src/platforms/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java deleted file mode 100644 index c237e178..00000000 --- a/src/platforms/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.caskeleton.grpc.ledger; - -import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * The ledger's Flyway scripts in version order, one SQL text per file for a test database. - * - *

One list for every PostgreSQL lane, so a new migration is applied by all of them or by none. - * The list is the tree on disk, not a copy of it: a hand-kept list let a V004 that nobody added to - * it go unapplied and unchecked by every lane (re-review 2026-11-03 round 3, RR3-02-04). Which file - * is a versioned migration, and in what order Flyway applies them, is the persistence-jpa testkit's - * {@link VersionedMigrationFiles}, the definition the main build's trees use; this lane compiles - * that file from there ({@code sharedMigrationFileSources} in this leaf's {@code build.gradle}) - * rather than keep a second regular expression of its own (re-review README 12, r6-b; r9). - */ -final class GrpcOperationLedgerMigrations { - - /** The ledger's tree from this leaf's directory, where the lanes run. */ - private static final Path TREE = Path.of("src/main/resources/db/migration/grpc"); - - /** The same tree on the classpath, where the scripts are read from. */ - private static final String LOCATION = "db/migration/grpc/"; - - private GrpcOperationLedgerMigrations() {} - - /** - * The file name of every versioned migration in the tree ({@code V__.sql}), in - * Flyway's order: by version, its parts compared as numbers. - */ - static List inOrder() throws IOException { - return VersionedMigrationFiles.inVersionOrder(TREE).stream() - .map(file -> file.getFileName().toString()) - .toList(); - } - - /** Every migration's SQL in version order, one script per file. */ - static List all() throws IOException { - return before(null); - } - - /** - * The SQL of every migration before the one named, in version order, one script per file. Run - * each as a statement of its own, the way Flyway runs a file: one string holding many files runs - * in one implicit transaction, where PostgreSQL refuses a file Flyway runs outside one — a - * concurrent index build (re-review 2026-11-03 round 7, RR7-03-01). - */ - static List before(String fileName) throws IOException { - List scripts = new ArrayList<>(); - for (String name : inOrder()) { - if (name.equals(fileName)) { - break; - } - scripts.add(read(name)); - } - return scripts; - } - - /** One migration's SQL, by its file name. */ - static String named(String fileName) throws IOException { - if (!inOrder().contains(fileName)) { - throw new IOException("no gRPC operation-ledger migration is named " + fileName); - } - return read(fileName); - } - - /** - * Whether Flyway is told to run the migration in a transaction: false only when the {@code - *