refactor(platforms)!: gRPC 플랫폼을 별도 repo grpc-library로 옮기고 지운다

템플릿 repo 안에 프로젝트 계층이 아닌 라이브러리가 있었다. gRPC 플랫폼
(src/platforms/grpc, grpc-advanced)과 그것만을 위한 두 번째 Gradle 빌드
(src/platforms/optional-build)는 템플릿 어느 leaf도 쓰지 않는데,
registry 9행, workflow job 넷과 단계 하나, build-logic 플러그인 둘,
카탈로그·SpotBugs 항목, 문서 열두 개를 템플릿이 함께 지고 있었다.

소유자 결정(2026-11-07, design-docs repo-structure/README.md 3.5절,
05-library-repos.md Q1~Q17 승인)대로 라이브러리마다 별도 repo로 옮긴다.
gRPC는 템플릿 소비자가 없어 먼저 옮기고, 템플릿은 지우기만 한다(Q13).
코드와 이력은 grpc-library repo에 filter-repo로 옮겼다(옮긴 폴더의 트리
해시가 이 기준 커밋 22df3525와 같다).

지운 것:
- src/platforms/grpc, grpc-advanced, optional-build(343파일)
- registry의 "build": "optional-grpc" 9행
- ci-quality-gates.yml job optional-platforms·grpc-proto-buf와 그 needs,
  integration-main.yml optional 성능 단계와 job
  grpc-optional-platform-integration, release.yml job
  grpc-stable-release-gate와 이미지 job의 needs 한 줄
- build-logic ca.grpc-platform-module·ca.optional-architecture-registry,
  MainBuild(두 번째 빌드에서 주 빌드를 찾던 것)와 ArchitecturePlugin의
  optional 분기. 도구 설정·이미지 목록·registry는 Gradle 루트에서 찾는다
- 카탈로그 protobufPlugin·protobuf-java-grpc·protoc·plugin protobuf(Q14:
  채택 전이라 grpc-library 좌표도 넣지 않는다), SpotBugs 제외의 gRPC 줄
- 옮긴 문서: ADR-GRPC 7개, docs/compatibility/(폴더째), gRPC runbook 둘,
  gRPC 설계서. 리뷰·기록 본문은 고치지 않았다(Q15). 기록 하나의 머리
  블록 「현재 정본」만 새 자리를 말하게 했다
- DeveloperExperienceContractTest의 optional 빌드 lane 계약 시험,
  adopter API 표면 검사의 optional-build 제외 경로

남긴 것: adapter:inbound:grpc(io.grpc를 직접 쓰고 플랫폼을 쓰지 않는다),
src/platforms/messaging(다음 분리 작업), registry의 build 칸 지원
(ModuleRegistry, 일반 기능).

살아 있는 문서: README, docs 지도, capability-status, work/delegate·
gates·decisions(새 행 「라이브러리 repo」)·defect-patterns·
review-criteria(경계 밖 파일을 경로로 읽는 결합을 결함 후보로),
manual 04, jpa migration-guide, build-logic AGENTS·README, testkit 주석.
새 docs/work/reference/related-repos.md가 라이브러리 repo 목록과 같이
고치는 법을 둔다. 파생 서비스 안내는 docs/upgrade 3.8절 B-55·B-56.

위험: 파생 서비스가 이 경로를 고쳤으면 수정 대 삭제 충돌이 난다
(tech-log-backend는 플랫폼을 받은 적이 없다, 설계 12절). 분리 직전
커밋 태그 pre-library-split(설계 12.2절)은 이 브랜치 권한 밖이라 달지
않았다.

검증: desktop 게이트 결과는 PR 본문(ci, mainCheck 계열, releaseCheck,
compose smoke, 빠른 시작). 문서 검사 셋 rc=0.

BREAKING CHANGE: src/platforms/grpc*·optional-build, :grpc:*·:grpc-advanced:*
프로젝트, ca.grpc-platform-module, 카탈로그 protoc·protobuf-java-grpc·plugin
protobuf가 없다. 쓰던 서비스는 grpc-library 좌표 com.hyeonworks.grpc로
받는다(docs/upgrade/2026-11-maturity-review.md 3.8절).
Refs: design-docs repo-structure/05-library-repos.md 13.1절 1·2단계
This commit is contained in:
DongHyeonka
2026-11-08 11:29:47 +09:00
parent 22df352510
commit 5e204e6a43
397 changed files with 122 additions and 33326 deletions
+1 -66
View File
@@ -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
-35
View File
@@ -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
-44
View File
@@ -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 <task>` 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
+2 -2
View File
@@ -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 <FeatureName>`으로 만들고 [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. 별도 repo에서 받는 라이브러리의 패키지(`com.hyeonworks.*`)는 바꾸지 않는다. 라이브러리 목록은 [관련 저장소](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와 운영 문서를 새 서비스 설명으로 고친다.
-1
View File
@@ -35,7 +35,6 @@
| `architecture/` | 공개 API 표면 스냅숏(`*-api-surface.txt`). API surface 검사가 대조한다 |
| `security/` | 기본 공개 경로 스냅숏. `verifyPublicPathSnapshot`이 대조한다 |
| `observability/` | 구조화 로그 필드 사전 |
| `compatibility/` | gRPC 플랫폼 지원 매트릭스(무엇에 대해 인증했고 무엇은 지켜보기만 하나) |
### 영역 운영 문서
@@ -1,57 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **결정 기록** 본문은 결정한 때의 내용이다(번역은 뜻을 바꾸지 않았다). 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
- 상태: 채택
- 작성일: 2026-08-30
- 요약: gRPC 플랫폼을 adapter leaf 하나가 아니라 registry에 등록한 family로 낸다는 결정이다.
- 현재 정본: `docs/compatibility/grpc-support-matrix.md`
<!-- 머리 블록 끝 -->
# ADR-GRPC-001: gRPC 플랫폼은 adapter leaf 하나가 아니라 등록된 family로 싣는다
- 상태: 채택
- 날짜: 2026-08-30
- 범위: `:grpc:*`, `:grpc-advanced:*`, `src/config/architecture/modules.json`
## 배경
두 원본 계획은 자기 API, SPI, 어댑터, 조립 루트를 가진 타입 안전 gRPC 실행 플랫폼을 설명한다: `modules/grpc` 아래
Stable 모듈 열다섯과 `modules/grpc-advanced` 아래 Advanced 모듈 열여섯, Gradle Kotlin DSL, 패키지
`io.backend.skeleton.grpc`, Spring Boot 4.1 기준.
그 배치는 여기 하나도 없다. 이 저장소는 Groovy DSL, leaf 목록을 가진 실패하면 닫히는 모듈 registry, 패키지 루트
`dev.caskeleton`, Spring Boot 4.0.8을 쓴다. 계획은 이것을 예상한다: 마지막 Global Constraint가, 저장소 구조가 다르면
파일 경로를 다시 대응시키고 공개 계약·불변식·시험의 뜻은 바꾸지 않는다고 말한다.
고를 수 있는 모양은 둘이었다. 플랫폼을 기존 `:adapter:inbound:grpc` leaf에 패키지로 접어 넣기 — JPA, GraphQL,
WebSocket, HTTP 플랫폼이 여기서 그렇게 했다 — 또는 `messaging:*`를 등록한 방식대로 family로 등록하기.
## 결정
family로 등록한다: `src/grpc/` 아래 Stable leaf 열둘과 `src/grpc-advanced/` 아래 Advanced leaf 여섯.
결정을 가른 성질은 이것이 이 애플리케이션의 계층이 아니라는 점이다. 루트 `CLAUDE.md`는 이미 `messaging:*`를 "a
vendored messaging platform: a product with its own API, SPI, adapters and composition boundary, not a layer of this
application"(들여온 메시징 플랫폼: 자기 API, SPI, 어댑터, 조립 경계를 가진 제품이고 이 애플리케이션의 계층이
아니다)이라고 설명하고, gRPC 플랫폼은 같은 이유로 같은 모양이다 — 애플리케이션은 라이브러리에 닿듯, 애플리케이션이
가진 포트를 거쳐 그것에 닿아야 한다. 패키지가 된 네 플랫폼은 모두 이 애플리케이션의 계층이다. 이것은 아니다.
`src/grpc/`와 `src/grpc-advanced/`의 분리는 정리용이 아니다. Stable 계획은 Stable starter의 빌드가 Advanced 모듈에
닿으면 실패해야 한다고 요구하고, Gradle 경로 접두어를 따로 두면 그것이 리뷰 메모가 아니라
`verifyCleanArchitectureDependencies` 실패가 된다: `grpc-spring-boot-starter`의 registry 항목은 advanced id를 하나도
대지 않고, 소리 없이 얻을 수도 없다.
## 결과
**registry가 leaf 44개에서 62개로 늘었다.** 큰 registry 변경이고, 일부러 한곳에서 했다. 새 leaf는 모두
`runtime_memberships: []`라서, 두 번째로 명시한 결정이 옮기기 전까지 아무것도 실리지 않는다.
**advanced 경계는 두 번 검사한다.** 빌드 때 registry가 한 번, 런타임에 `GrpcStableBuildInvariant`가 한 번. fat jar나
shaded artifact는 registry가 보지 못하는 무언가가 조립하기 때문이다.
**testkit 모듈 넷은 시험 lane 넷이 됐다.** 계획이 나눈 이유는 프로세스 안 결과를 네트워크 결과로 착각하지 못하게
하려는 것이다. 이 저장소는 그것을 `ca.strict-test-lane`으로 나타낸다. 그 lane은 아무것도 찾지 못하면 실패하고,
up-to-date 결과를 내주지 않는다. `GrpcEvidenceGrade`가 코드 안에서 같은 규칙을 지키므로, 보고서가 계약 실행을 전송
증거로 인용할 수 없다.
**codegen은 배선하지 않았다.** ADR-GRPC-002를 본다.
@@ -1,72 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **결정 기록** 본문은 결정한 때의 내용이다(번역은 뜻을 바꾸지 않았다). 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
- 상태: 대체됨
- 작성일: 2026-08-30
- 요약: protoc와 Buf CLI 없이 스키마를 관리하려던 결정이다. 2026-09-28 Gradle protobuf plugin과 buf로 바뀌었다.
- 현재 정본: `docs/compatibility/grpc-support-matrix.md`
- 대체됨: `docs/capability-status.md`
<!-- 머리 블록 끝 -->
# ADR-GRPC-002: schema 관리는 protoc 없이, Buf CLI 없이 돈다
- 상태: **대체됨(2026-09-28)** — 2026-09-25 리뷰 후속의 소유자 결정 18
- 날짜: 2026-08-30
- 범위: `:grpc:grpc-proto-contract`, `:grpc:grpc-codegen`(둘 다 지움)
> **대체됨.** 정규식 `.proto` 검증기와 Buf 규칙의 Java 재구현은 지웠다. schema는 이제 `:grpc:grpc-contract`
> (`src/grpc/grpc-contract/src/main/proto`)에 있고 Gradle protobuf 플러그인(`com.google.protobuf`, 버전은
> `src/gradle/libs.versions.toml`에 고정. protoc와 protobuf-java runtime은 둘 다 `protobufGrpc`)이 컴파일한다. 생성된
> 소스는 그 leaf에서만 Spotless, Checkstyle, Error Prone에서 뺀다. `buf lint`와 `buf breaking`
> (`src/grpc/grpc-contract/buf.yaml`, STANDARD lint, FILE breaking)은 CI의 `.github/workflows/ci-quality-gates.yml`
> job `grpc-proto-buf`에서 돈다. proto organization은 `caskeleton`이다(예전에는 `hyeonworks`). 아래 글은 원래 결정의
> 기록으로 남긴다.
## 배경
Stable Task 8부터 11은 proto 문체 규칙, Buf format·lint·breaking 관리, Java codegen 소유자 하나, 그리고 쓰는 쪽
컴파일 결과가 릴리스를 막는 descriptor artifact를 요구한다.
그 Task가 이름을 대는 도구 중 둘이 이 toolchain에 없다. Buf CLI는 설치돼 있지 않다. 그리고 `protoc`는 Gradle
protobuf 플러그인으로 쓸 수 있지만, 이 저장소의 모든 leaf는 google-java-format을 쓴 spotless, checkstyle, HIGH
confidence의 SpotBugs, Error Prone, `-Werror`를 통과하는데 — 생성된 protobuf 소스는 그중 어느 것도 통과하지 못한다.
codegen을 켜면 source set 하나를 품질 게이트 다섯에서 빼야 한다.
그런 예외에는 선례가 있다: `jmh` source set은 `spotbugsJmh`와 `checkstyleJmh`를 끄고 Error Prone도 끈다. 그러니 빼는
길은 있다. 하지만 그것은 Task 하나를 위해 leaf의 품질 기준선에 대해 내리는 결정이고, 이 일이 바꾸라고 받은 범위
밖이다.
`adapter:inbound:grpc`에도 반대 방향으로 기록된 결정이 있다: 그 `CLAUDE.md`는 쓰는 기능 모듈이 자기 schema를 가져야
한다는 이유로 그 leaf에서 protobuf 플러그인과 `.proto`를 금지한다.
## 결정
`.proto` 소스를 커밋하고, Task가 요구하는 모든 규칙을 protoc 실행도 Buf CLI 호출도 없이 실행되는 Java로 구현한다.
`GrpcProtoContractValidator`는 `.proto` 글을 읽고 다음을 강제한다: proto3 문법, `{organization}.{domain}.v{major}`
패키지 규칙, `java_multiple_files`, 손으로 쓴 것과 겹치지 않는 생성 Java 패키지, `_UNSPECIFIED` enum 0값, 받은 삭제
이력과 대조한 `reserved` 선언, well-known type 허용 목록, map 필드 허용 목록. 자기 시험에서 커밋한 schema에 대고
돌므로, 출하하는 `.proto` 파일은 장식이 아니라 살아 있다.
`GrpcBufPolicy`는 breaking gate를 Buf의 `FILE` category로 고정하고, 규칙을 따르는 pipeline이 등록하는 lifecycle 단계
넷을 이름으로 댄다. `GrpcCodegenManifest`는 codegen 소유자를 하나로 고정하고 리터럴 생성기 버전을 거절한다.
`GrpcDescriptorArtifact`, `GrpcConsumerFixture`, `GrpcSchemaArtifactPublisher`는 schema hash, descriptor digest, 쓰는
쪽별 소스 깨짐 보고를 싣고, 쓰는 쪽을 깨뜨리는 게시나 이미 릴리스한 버전을 다른 바이트로 다시 게시하는 것을
거절한다.
커밋한 `buf.yaml`도 같은 규칙을 적으므로, CLI가 있는 환경에서 돌리면 같은 판정에 닿는다.
## 결과
**불변식은 강제하고, 과정은 돌리지 않는다.** Task 8부터 11이 다루는 모든 것 — 어떤 schema 변경을 거절하는지, 어떤
쓰는 쪽 깨짐이 릴리스를 막는지, 생성을 누가 가지는지 — 이 여기서는 빌드로 검사하는 규칙이다. 빠진 것은 protoc
호출과 Buf 바이너리다.
**codegen을 켜는 것은 한계 있는 변경이다.** `GrpcCodegenManifest.caSkeleton()`이 이미 실제 플러그인 설정이 만족해야
할 소유자, 관리되는 버전 출처, 빌드 디렉터리 출력 경로, 겹치지 않는 패키지 정책을 이름으로 댄다. 할 일은 source set
예외와 플러그인 블록이지 재설계가 아니다.
**fixture는 텍스트 codec을 쓴다.** `GrpcTextCodec`이 testkit에 UTF-8 marshaller를 줘서, 프로세스 안 lane과 Netty
lane이 생성된 stub 없이 interceptor, status 대응, metadata 한계, stream 순서를 시험할 수 있다. 그 계약은 메시지
모양이 아니라 플랫폼과 전송의 성질이므로 바꿔 넣어도 잃는 것이 없다 — 그리고 lane이 codegen이 들어온 뒤가 아니라
오늘 돈다.
@@ -1,54 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **결정 기록** 본문은 결정한 때의 내용이다(번역은 뜻을 바꾸지 않았다). 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
- 상태: 채택
- 작성일: 2026-08-30
- 요약: 전송·업무·스트림 증거를 서로 대신하지 않는 세 축으로 본다는 결정이다.
- 현재 정본: `docs/compatibility/grpc-support-matrix.md`
<!-- 머리 블록 끝 -->
# ADR-GRPC-003: 전송·업무·stream 증거는 세 축이고, 어느 것도 다른 것을 뜻하지 않는다
- 상태: 채택
- 날짜: 2026-08-30
- 범위: `:grpc:grpc-core-api`, `:grpc:grpc-runtime`(예전 `grpc-policy`), `:grpc:grpc-testkit`
## 배경
실패한 RPC는 status code를 낸다. 그리고 status code는 호출자가 실제로 가진 질문의 답이 아니다. 변경 요청의
`DEADLINE_EXCEEDED`는 변경이 일어났는지 말하지 않는다. 요청을 보낸 뒤의 `UNAVAILABLE`은 서버가 그것을 한 번도 보지
않았다고 말하지 않는다. 응답 header가 도착했다고 트랜잭션이 커밋된 것은 아니다.
그 하나하나가 그럴듯한 추론이 중복 쓰기나 잃은 쓰기를 낳는 자리이고, 성공 경로만 시험하는 시험에서는 하나도 보이지
않는다.
## 결정
일어난 일을 서로 독립인 세 축으로 모델링하고, 축 사이의 추론을 거절한다.
`GrpcTransportEvidence`는 client가 wire에서 본 것을 기록하고, `NOT_SENT` — client가 자기 보내기가 실패하는 것을 봤다
— 와, 아무것도 모르는 다른 모든 경우인 `UNOBSERVED`를 구별한다. `GrpcBusinessEvidence`는 애플리케이션이 확인한 것을
기록하고, `COMMIT_UNKNOWN`은 자리표시가 아니라 실제 상태다. `GrpcStreamEvidence`는 sealed 계층이고, 비어 있지 않은
경우는 모두 위치를 싣는다. 마지막 순번 없는 「부분」은 이어 가지도 맞춰 보지도 못하기 때문이다.
`GrpcExecutionEvidence`는 셋을 모두 가지고, 아무도 볼 수 없었을 조합을 거절한다: stream 증거가 있는 unary 호출, 또는
client가 보내기 실패를 봤는데도 업무 증거를 실은 요청. 응답 header를 확인된 커밋으로 올리는 것은
`withResponseHeadersSeen`을 고쳐야만 할 수 있다. 그것은 interceptor 안의 그럴듯한 한 줄이 아니라 메서드 하나다.
`GrpcCompletionOutcome.forMutation`이 호출자가 결론 내릴 수 있는 것을 끌어내고, 변경 요청의 `DEADLINE_EXCEEDED`와
보낸 뒤의 `UNAVAILABLE`을 기본으로 `COMPLETION_UNKNOWN`으로 둔다.
실패 모델과 관측 규약이 같은 타입을 쓰므로, 사고 때 호출 하나에 대한 설명이 둘이 아니라 하나다.
## 결과
**재시도 결함의 한 종류를 아예 나타낼 수 없게 된다.** `GrpcRetryEligibility`는 세 축 모두와 멱등성 profile을 읽는다.
status만으로는 입력이 아니므로, 호출자는 status만 보고 「재시도」에 닿을 수 없다.
**장애 lane에 검사할 것이 생긴다.** `GrpcTransportEvidenceClassifier`가 client의 관찰을 증거로 바꾸고, 관찰하지 않은
상태에서 `NOT_SENT`를 추론하기를 거절한다 — 그리고 lane은 mock이 아니라 호출 중간에 끊은 실제 연결에 대고 그것을
시험한다.
**호출자는 세 번째 결과를 다뤄야 한다.** `COMPLETION_UNKNOWN`은 실패도 성공도 아니고, 둘 중 하나로 다루는 호출자는
틀렸다. `GrpcOperationStatusQuery`와 `GrpcCompletionReconciler`는 그것을 푸는 일이 호출자에게 맡긴 숙제가 아니라
지원하는 경로가 되게 하려고 있다.
@@ -1,112 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **결정 기록** 본문은 결정한 때의 내용이다(번역은 뜻을 바꾸지 않았다). 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
- 상태: 채택
- 작성일: 2026-08-30
- 요약: 재시도 주인은 하나이고 키가 있는 변경은 영속 원장이 필요하다는 결정이다.
- 현재 정본: `docs/compatibility/grpc-support-matrix.md`
<!-- 머리 블록 끝 -->
# ADR-GRPC-004: 재시도 소유자는 하나이고, 키가 있는 변경에는 durable 원장이 필요하다
- 상태: 채택
- 날짜: 2026-08-30
- 범위: `:grpc:grpc-runtime`(예전 `grpc-policy`), `:grpc:grpc-operation-ledger-jpa`, `:grpc:grpc-core-api`
## 배경
gRPC 호출을 재시도할 수 있는 계층이 셋 있다: 애플리케이션, channel의 service config, service mesh. 그 효과는 곱해진다.
계층마다 세 번 시도하면 호출 하나에 요청 스물일곱 개이고, 그 부하는 의존 대상이 이미 실패하고 있을 바로 그때 온다.
따로, 되풀이해도 안전한 변경에는 그것이 돌았다는 기록을 둘 곳이 필요하다. 없으면 응답을 잃은 뒤의 재시도는 효과를
겹치게 하거나 버리게 되고, 나중에 둘을 구별할 것이 없다.
## 결정
**channel마다 재시도 소유자는 정확히 하나다.** `GrpcRetryOwner`에는 `NONE`을 포함해 값이 넷 있고, `NONE`은 빠뜨림이
아니라 결정이다. `GrpcServiceConfigPolicy`는 소유자가 mesh이거나 아무도 아닐 때 프로세스 안 재시도 항목을 거절하고,
`GrpcRetryOwnershipValidator`는 service config의 메서드 이름을 정책 catalog와 대조한다 — 이름이 바뀐 메서드는 그 재시도
항목이 소리 없이 아무것과도 맞지 않게 되고, 그 메서드는 channel 기본값으로 돈다.
**재시도 자격은 메서드, 증거, status를 함께 읽는다.** `GrpcRetryEligibility`는 멱등이 아닌 메서드를 바로 거절하고,
stream이 앞부분을 전달한 호출을 모두 거절하며, 변경 요청의 `DEADLINE_EXCEEDED`나 보낸 뒤의 `UNAVAILABLE`을 재시도가
아니라 「먼저 완료를 풀어라」로 바꾼다.
**키가 있는 변경은 호출자 키와 durable 원장이 둘 다 있을 때만 재시도할 수 있다.** `GrpcOperationLedger`는
`grpc-core-api`의 포트라서, 정책 계층이 데이터베이스에 의존하지 않고 durable 멱등성을 요구할 수 있다. 그 `claim` 계약은
unique 제약에 대한 원자적 insert-or-read 하나다: `JpaGrpcOperationLedger`는 먼저 insert하고 제약 위반이면 읽는다.
read-then-insert 구현에는 그것이 닫으려는 경쟁만큼 넓은 창이 있고, 두 시도를 동시에 돌리지 않는 모든 시험을
통과하기 때문이다.
identity는 호출자 fingerprint + 전체 메서드 + hash한 키다. 셋 모두 꼭 필요하다: 호출자가 없으면 한 테넌트의 키가 다른
테넌트의 쓰기를 막는다. 메서드가 없으면 operation 사이에서 다시 쓴 키 때문에 둘째가 첫째의 재생이 된다.
## 결과
**예산이 재시도를 traffic의 비율로 묶는다.** `GrpcRetryBudget`은 모든 것이 실패할 때 재시도가 거의 없는 쪽으로
떨어진다. 그것이 의존 대상이 회복하게 하는 동작이다.
**원장과 변경은 함께 커밋해야 한다.** `JpaGrpcOperationLedger`는 일부러 트랜잭션 애너테이션을 달지 않는다:
`REQUIRES_NEW`는 claim을 자기 트랜잭션에 넣어서, 쓰기는 durable한데 claim은 아닌 창을 다시 들인다.
**claim은 키를 영원히 막지 않고 만료된다**(review 2026-11-01, 03-10). claim TTL이 지난 뒤에도 `IN_PROGRESS`인 claim은
죽은 주인이 버린 것으로 보고, 같은 요청의 다음 재시도가 `GrpcOperationLedger.reclaimStale`로 넘겨받는다 — 조건부
`UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff` 하나라서, 동시에 넘겨받기 둘이 오면 정확히 하나가 이긴다.
`reclaimFailed`와 같은 모양이다. TTL은 `GrpcIdempotencyInterceptor`의 `claimTtl` 인자이고, 키가 있는 모든 메서드의
deadline보다 길지 않으면 만들 때 거절한다. 03-11 후속부터 starter는 `app.grpc.platform.operation-ledger-enabled=true`이면
interceptor를 조립하고 TTL을 `app.grpc.platform.operation-ledger-claim-ttl`(기본 5m)에서 가져온다. 생성자가 거절하는
TTL은 그 키 이름을 대며 기동을 실패시키고, `GrpcOperationLedger` bean 없이 flag를 켜도 기동이 실패한다.
넘겨받기가 안전한 것은 커밋을 변경 자신의 트랜잭션 안에서 기록하기 때문뿐이다: 그러면 아직 `IN_PROGRESS`인 claim은
변경이 한 번도 커밋되지 않았다는 뜻이다. 둘을 따로 커밋하는 채택자는 버려진 claim을 모르는 결과로 만들고, 넘겨받기가
변경을 두 번 돌릴 수 있다. 그저 느린 주인을 넘겨받아도 같은 일이 생긴다. 그래서 TTL은 deadline만이 아니라 키가 있는
가장 느린 메서드보다 길어야 한다.
버린 것: heartbeat lease를 단 owner token(outbox lease 모델) — 키가 있는 메서드가 어떤 고정 TTL보다 오래 돌 수 있을 때만
필요하다. 그런 메서드가 생기면 다시 본다. 낡은 행을 지우는 sweeper job — 이 family에 없는 scheduler가 필요하고,
claim을 지우면 다음 재시도가 시도를 버렸다는 기록 없는 새 claim이 된다.
**넘겨받긴 주인은 claim token으로 막는다**(re-review 2026-11-03, RR-02-04). 넘겨받기가 죽었다고 보는 주인은 그저 느릴
수 있다. 어느 시도가 claim을 쥐었는지 모르면, 그 주인의 늦은 `markFailed`가 새 시도의 claim을 `FAILED_TERMINAL`로
만들었고, 다음 재시도가 그것을 다시 claim해서 두 시도가 동시에 변경을 돌렸다. 늦은 `markCommitted`는 새 시도 옆에서
커밋했다. 이제 모든 claim은 `GrpcClaimToken`(`claim_attempt`, migration V003)을 싣는다: 첫 claim은 1이고,
`reclaimFailed`나 `reclaimStale`마다 하나씩 늘어난다. `decide`는 `PROCEED`에서 그것을 돌려주고, `recordCommit` /
`recordFailure`가 그것을 되돌려 준다. 커밋이나 실패는 조건부
`UPDATE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt` 하나다: claim을 잃은 시도의 커밋은 예외로 거절해서
그 업무 트랜잭션이 롤백되고, 그런 시도의 실패는 무시한다(`markFailed`가 false를 돌려준다). 같은 조건부 update가 JPA
커밋 경쟁도 닫는다 — load-check-save에서는 둘 다 `IN_PROGRESS`를 읽은 커밋 둘이 둘 다 썼다. 이제 정확히 하나만 맞는다.
insert와 read 사이에 충돌 행이 지워진 claim은 호출을 실패시키지 않고 insert를 한 번 다시 시도한다.
`release(identity, claimToken)`도 같은 방식으로 막는다(re-review 2026-11-03 round 2, RR-01-15): 조건부
`DELETE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt`이고 지웠는지를 돌려준다. 예전에는 키만으로 지웠기
때문에, 아무 호출자나 그것을 쥔 시도의 claim이나 재시도가 재생하는 끝난 레코드를 지울 수 있었다. counter는 행 안에
있으므로 지운 행의 키는 다시 attempt 1에서 시작한다: token은 행 하나의 시도들을 가르지, 삭제를 넘는 시도들을 가르지
않는다. 그래서 두 삭제를 모두 제한한다 — release는 주인이 사라졌다고 아는 claim에만, purge는 어떤 재시도보다 오래 전에
끝난 행에만. 버린 것: 포트에서 `release`를 빼기(`markFailed` 뒤 `reclaimFailed`는 counter를 지키지만, 다른 요청을 위해
키를 풀어야 하는 배포에는 다른 길이 없다), counter를 지키는 tombstone 행(지울 두 번째 상태가 생기는데, 그 창은 두 제한이
이미 닫는다).
token으로 claim 시각(`WHERE claimed_at = :claimedAt`)을 쓰는 안보다 이것을 골랐다. 시각은 열이 따로 필요 없지만,
PostgreSQL은 마이크로초를 저장하고 `Instant`는 나노초를 싣는다. 그래서 호출자가 쥔 token과 저장된 것이 반올림만큼
다를 수 있고, 두 프로세스의 시계가 두 시도에 같은 시각을 줄 수 있다. counter에는 두 문제가 다 없다. 위 heartbeat lease는
앞과 같은 이유로 계속 버린다. token은 그것 없이 막는다.
**`operation-ledger-enabled=true`가 약속하는 것(03-11 (b), 2026-11-03 기록, RR-02-07).** 2026-11-01 리뷰는 (a) flag를
지우고 원장 bean이 있는지로 판단하기와 (b) flag를 두고 starter가 그것으로 판정 함수를 조립하기를 내놓았다. (b)를
지킨다: 조립과 TTL 검증이 채택자마다가 아니라 한곳에 있다. (a)는 거짓 약속을 없애되 조립까지 함께 없애기 때문에
버렸다. 한계는 남고, 운영자가 그것을 만나는 곳에 적는다: starter는 서버를 만들지 않으므로 flag는 판정 함수만
조립하고, 채택자의 `IDEMPOTENCY` 단계 interceptor나 service adapter가 `decide`와 `recordCommit`을 부를 때 비로소 키가
지켜진다. 키가 있는 메서드에 대한 `GrpcPlatformStartupValidator`의 거절이 바로 그것을 말한다. 돌고 있는 프로세스는 그
단계가 있는지 볼 수 없으니, validator는 그것을 검사한다고 주장하지 않는다.
**끝난 행은 보존 기간 뒤에 지우고, 진행 중인 행은 절대 지우지 않는다**(03-10 후속).
`GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)`는 cutoff 전에 끝난 `COMMITTED`나 `FAILED_TERMINAL` 행을 오래된
것부터 많아야 `limit`개 지운다 — PostgreSQL에서는 migration V002의 부분 index가 받쳐 주는 한계 있는
`DELETE … WHERE storage_key IN (SELECT … LIMIT … FOR UPDATE SKIP LOCKED)` 하나다.
`GrpcOperationLedgerRetention.purgeExpired(now)`가 `app.grpc.platform.operation-ledger-retention`(기본 24h, HTTP 멱등성
재생 TTL)을 batch로 적용한다. 레코드가 지워진 뒤의 재시도는 새 claim이고 다시 돈다. 그래서 보존 시간은 호출자의 재시도
창보다 길어야 한다. 지우기 일정은 채택자가 잡는다. starter는 정책만 조립한다. 예약된 bean은 모든 배포에 scheduler를
강요하고, starter는 어느 replica가 돌려야 하는지 알 수 없기 때문이다.
**다른 요청에 다시 쓴 키는 중복이 아니라 호출자 오류다.** 저장된 요청 fingerprint가 그것을 소리 없이 첫 요청의 답을
돌려주는 대신 `FAILED_PRECONDITION`으로 바꾼다.
@@ -1,52 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **결정 기록** 본문은 결정한 때의 내용이다(번역은 뜻을 바꾸지 않았다). 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
- 상태: 채택
- 작성일: 2026-08-30
- 요약: 서버 스트림은 writer 하나, 제한된 큐, 추측하지 않는 resume로 다룬다는 결정이다.
- 현재 정본: `docs/compatibility/grpc-support-matrix.md`
<!-- 머리 블록 끝 -->
# ADR-GRPC-005: stream마다 쓰는 쪽 하나, 한계 있는 queue, 짐작하기를 거절하는 resume
- 상태: 채택
- 날짜: 2026-08-30
- 범위: `:grpc:grpc-runtime`(예전 `grpc-policy`)
## 배경
`StreamObserver`는 thread-safe가 아니다. 두 producer가 동시에 `onNext`를 부를 때의 실패는 예외가 아니다 — 섞인 바이트이고,
client는 그것을 깨진 메시지로, 더 나쁘게는 받지 말았어야 할 유효한 메시지로 decode한다.
server stream에는 건강해 보이는 방식으로 틀리기 쉬운 성질이 둘 더 있다. 뒤처진 소비자는 stream을 끝내거나 메시지를 소리
없이 잃는데, 둘째는 client에게 멀쩡해 보이지만 변경이 빠진 stream을 남긴다. 그리고 재연결은 서버가 아직 재생할 수 있는
위치에서 이어 가거나, 더는 없는 것을 건너뛴다.
## 결정
**쓰는 쪽 하나가 비우는 한계 있는 queue.** `GrpcSerializedStreamWriter`는 어느 스레드에서든 메시지를 받고, synchronized인
`flush`에서만 전송에 넘긴다. `write`가 `ACCEPTED`를 돌려주는 것은 줄 세웠다는 뜻이고, 이름을 일부러 `sent`로 하지
않았다: 전송 호출은 바이트를 넘기자마자 돌아오므로, 여기 어떤 메서드도 전달을 정직하게 알릴 수 없다.
**메시지 한계와 바이트 한계를 둘 다.** 하나만 두면 다른 차원으로는 한계가 없다. `GrpcFlowControlPolicy`는 전송 자신의
readiness 신호도 받는다. queue 한계에만 기대는 쓰는 쪽은 메모리를 할당할 수 있는 만큼 빨리 만들어 내기 때문이다.
**느린 소비자에게는 끝내기가 기본이다.** `GrpcSlowConsumerPolicy.DROP_OLDEST`는 업무 뜻이 손실을 견디는 feed를 위해
있고 기본값이 아니다. client는 버려진 메시지를 알아챌 수 없기 때문이다: client가 보는 순번은 보내진 것의 순번이다.
**resume은 꾸며 내지 않고 거절한다.** `GrpcStreamGapDetector`는 서명됐고 만료되지 않았으며 호출자·필터 fingerprint가
지금 요청과 맞는 token을 요구하고, snapshot version이 움직인 token을 거절하며, cursor가 보존한 이력보다 앞서면
`FULL_RESYNC_REQUIRED`를 돌려준다. `GrpcResumeToken`은 key id를 싣는다. 그래서 서명 키를 바꿔도 아직 쓰이는 모든 token이
무효가 되지 않는다.
## 결과
**stream은 맨 payload가 아니라 envelope을 싣는다.** `GrpcStreamEnvelope`은 stream id, generation, 순번, snapshot version,
resume token을 가진다. resume, 빈틈 찾기, 비우기가 모두 위치와 generation을 필요로 하기 때문이다.
**시계는 하나가 아니라 넷이다.** `GrpcStreamLifetimePolicy`는 준비 deadline, idle timeout, 최대 지속 시간, heartbeat
간격을 나누고, 하나가 절대 울릴 수 없는 조합을 거절한다. 어느 둘을 합치든 익숙한 결함이 나온다: 최대 지속 시간으로 쓴
idle timeout은 건강하게 바쁜 stream을 죽인다.
**heartbeat는 살아 있다는 신호이고 그 밖의 무엇도 아니다.** 애플리케이션 확인 응답도 순서 보장도 아니다.
`GrpcStreamHeartbeat`가 누가 그것을 다르게 다시 쓸 법한 자리에서 그렇게 말한다.
@@ -1,67 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **결정 기록** 본문은 결정한 때의 내용이다(번역은 뜻을 바꾸지 않았다). 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
- 상태: 채택
- 작성일: 2026-08-31
- 요약: Stable discovery는 DNS와 정적 목록이고 Kubernetes에서는 누가 부하를 나누는지 profile이 정한다는 결정이다.
- 현재 정본: `docs/compatibility/grpc-support-matrix.md`
<!-- 머리 블록 끝 -->
# ADR-GRPC-006: Stable discovery는 DNS와 static이고, Kubernetes profile은 누가 분산하는지 이름으로 댄다
- 상태: 채택
- 날짜: 2026-08-31
- 범위: `:grpc:grpc-runtime`(예전 `grpc-discovery`, `grpc-client`)
## 배경
gRPC channel의 discovery 설정에는 런타임 증상이 없는 실패 방식이 있다: 동작은 하는데, 대시보드가 말하는 일을 하지 않는다.
구체적인 경우는 Kubernetes Service ClusterIP 위의 `round_robin`이다. Service는 가상 주소 하나라서 resolver가 endpoint 하나를
돌려주고 client 쪽 분산기는 돌려 가며 보낼 대상이 없다. kube-proxy는 연결할 때 pod를 고르고, HTTP/2 연결은 오래 살기
때문에, 그 client의 모든 요청이 연결이 사는 동안 같은 pod로 간다. 실패하는 것은 없다. 설정은 `round_robin`이라고 말하고,
metric은 요청이 pod가 아니라 client 사이에 퍼진 것을 보여 주며, 「client 쪽 부하 분산을 한다」는 결론은 아무도 확인할
계기가 없는 방식으로 틀렸다.
거울상 실수는 headless record 위의 `pick_first`다. 많은 pod 중 하나에 client를 묶는다.
따로, service mesh는 재시도를 누가 가지는지 바꾸고, mesh 라우팅을 더하면서 자기 재시도 정책을 빼지 않은 배포는 효과가
곱해지는 재시도자 둘을 가진다.
## 결정
**Stable resolver는 Static, DNS, Unix domain socket이고, Stable 부하 분산은 `pick_first`와 `round_robin`이다.**
`GrpcDiscoveryPolicyValidator.requireStableScheme`은 `xds`, `consul`, `etcd`, `eureka`를 이름으로 거절하고, 그것이 모르는
scheme이 아니라 자기 control plane과 승격 gate를 가진 Advanced capability라고 메시지로 말한다.
**짝 맞춤은 의도가 아니라 해석된 주소 수와 대조한다.** `GrpcResolverProfile`은 `expectedAddressCount`를 싣고,
`GrpcStableLoadBalancer.effective`가 그 수의 endpoint 위에서 정책이 무언가를 분산하는지 답한다. 주소 하나 위의
`round_robin` profile은 보고되는 위반이고, 그 메시지는 그것이 일어나지 않는 퍼뜨리기를 설명한다고 말한다.
**Kubernetes 배포는 자기 라우팅 모드를 이름으로 대고**, 그 모드가 분산기와 재시도 소유자를 둘 다 정한다.
`GrpcKubernetesRoutingMode`에는 값이 셋 있다 — `K8S_VIP`, `K8S_HEADLESS`, `MESH` — 그리고 `GrpcKubernetesProfile`은 재시도
소유자가 프로세스 안에서 재시도하는 mesh profile을 거절한다.
**오래 사는 stream을 싣는 profile은 재연결 예산과 readiness 비우기 유예를 밝혀야 한다.** stream은 사는 내내 client를 pod
하나에 묶으므로, 모든 rollout, eviction, scale-down이 그것을 끝낸다. `GrpcKubernetesProfileValidator`는 긴 stream을 싣는
VIP profile과, 재연결 예산보다 짧은 비우기 유예도 알린다 — 후자는 client가 다른 곳으로 재연결을 마치기 전에 pod가 응답을
멈춘다는 뜻이다.
**DNS profile은 새로 고쳐야 한다.** `GrpcResolverProfile`은 DNS에서 새로 고침 간격 0을 거절한다. 기동 때 한 번 해석한
channel은 한 시간 전에 없어진 주소로 계속 보내고, 그 결과인 `UNAVAILABLE`은 rollout이 끝난 지 한참 뒤에도 건강하지 않은
배포처럼 보인다.
## 결과
**validator는 하나가 아니라 둘이다.** `GrpcDiscoveryPolicyValidator`는 분산기가 자기가 볼 주소 위에서 무언가를 하는지
묻는다. `GrpcKubernetesProfileValidator`는 배포 모양, 재시도 소유자, stream 의무가 맞는지 묻는다. 배포는 resolver profile이
앞뒤가 맞으면서도 재시도를 두 곳에 둘 수 있다. 그래서 둘을 합치면 한 답이 다른 답을 가린다.
**`expectedAddressCount`는 어딘가에서 와야 한다.** 선언한 숫자이고, 선언은 틀릴 수 있다. 그래도 아무것도 비교하지 않는
대안보다 낫다: 틀린 선언은 누가 적어 둔 틀린 말이고, 빠진 선언은 아무도 묻지 않은 질문이다.
`GrpcChannelProfileValidator`는 기동 때 알 수 있는 곳에서는 해석된 수를 받고, 알 수 없는 곳에서는 짐작해서 아직 해석할 수
없는 이름에서 실패하는 대신 검사를 건너뛴다.
**xDS에는 닿을 수 있지만, 이 길로는 아니다.** xDS는 `grpc-advanced`(패키지 `resilience`/`xds`)에서 자기 capability flag와
운영 승인 뒤에 있고, `GrpcXdsStartupGuard.advertisableAsStableSupport()`가 false를 돌려주므로 Stable 지원 설명이 조용히
넓어질 수 없다. ADR-GRPC-ADV-001을 본다.
@@ -1,57 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **결정 기록** 본문은 결정한 때의 내용이다(번역은 뜻을 바꾸지 않았다). 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
- 상태: 채택
- 작성일: 2026-08-30
- 요약: gRPC 고급 기능마다 따로 플래그·등급·승격 기준을 둔다는 결정이다.
- 현재 정본: `docs/compatibility/grpc-advanced-support-matrix.md`
<!-- 머리 블록 끝 -->
# ADR-GRPC-ADV-001: advanced capability마다 자기 flag, 자기 등급, 자기 승격이 있다
- 상태: 채택
- 날짜: 2026-08-30
- 범위: `:grpc-advanced:*`
## 배경
advanced 계획은 capability 열여섯을 다룬다. 그것들이 함께 가져오는 것은 몇 자릿수씩 다르다. gRPC-Web은 proxy를 더한다.
Reactor는 의존 하나를 더한다. xDS는 control plane, 그 장애 방식, 자기 보안 경계, 자기 버전 어긋남을 더한다. hedging은 운영
traffic을 겹친다.
그것들을 flag 하나로 묶으면 가장 싼 것을 켜는 일이 가장 무거운 것을 켜는 일과 같은 결정이 된다.
## 결정
**capability마다 flag 하나.** `ca-skeleton.grpc.advanced.<capability>.enabled` 아래에 있고, 기본은 모두 꺼짐이다.
**등급 넷.** `ADVANCED_STABLE`은 flag로 시작한다. `EXPERIMENTAL`은 따로 운영 승인도 필요하다. flag는 누가 그 기능을 원했다는
뜻이고, 승인은 누가 그 장애 방식이 다 밝혀지지 않았음을 받아들였다는 뜻이기 때문이다. `WATCH`는 아예 시작할 수 없다.
`DISABLED`는 거둬들인 것이다.
`GrpcAdvancedModuleGuard`는 세 거절 — flag 없음, 시작할 수 없는 등급, 운영 승인 없음 — 을 구별한다. 경우마다 고치는 법이
다르기 때문이다.
**승격 증거는 capability마다다.** `GrpcAdvancedPromotionEvidence`는 capability마다 record 하나라서, 어떤 승격도 다른 것을
끌고 가지 못한다. `GrpcAdvancedPromotionGate.capabilitiesDraggedAlong`은 빈 목록을 돌려주고, 그것은 주장이 아니라 시험한
성질이다. (2026-09-28: gate 클래스는 자기 시험 밖에서 부르는 것이 없어서 지웠다 — review 2026-09-24 S5-lead-4.
capability별 규칙은 `docs/runbooks/grpc-advanced-capabilities.md`의 리뷰 규칙으로 남는다.) 문턱은 둘이다:
`ADVANCED_STABLE`에는 7일 soak와 완전한 증거, Stable 기본값에는 30일. 후자는 모든 배포가 그 capability의 의존과 장애 방식을
받는다는 뜻이기 때문이다.
**기반 시설은 capability마다 이름으로 댄다.** `GrpcAdvancedInfrastructureTestkit`은 gRPC-Web에는 proxy가, Servlet에는
container가, xDS에는 멈출 수 있는 control plane이, Kotlin에는 toolchain이 필요하다고 적는다. 기반 시설 없이 도는 suite는
통과하고 아무것도 세우지 않는다. 없는 것보다 나쁘다.
## 결과
**Kotlin 어댑터는 여기서 실패하면 닫히고, 이유를 말한다.** 이 저장소에는 Kotlin toolchain이 없어서
`GrpcKotlinCompatibilityGate.supportableHere()`가 false를 돌려준다. 계약 요구 넷 — schema 출처 하나, coroutine 취소 전파,
Stable 한계 안의 Flow backpressure, 플랫폼 증거 타입 보존 — 은 검사할 수 있고 검사한다. 빠진 것은 compile lane뿐이다.
**Edition 2026은 그 watch 보고가 무어라 하든 쓸 수 없다.** `GrpcEdition2026Guard`는 보고에 따라 달라지지 않는다. 상태 기록이
사용까지 허락하게 두면, 누가 필드 넷을 SUPPORTED로 표시하는 순간 schema가 승격 결정도, 쓰는 쪽 옮기기도, ADR도 없이 그
edition으로 옮겨 가기 때문이다.
**xDS는 Stable 지원 설명의 일부가 아니다.** flag와 승인 뒤에서 동작한다. `GrpcXdsStartupGuard.advertisableAsStableSupport()`가
false를 돌려주므로 support matrix가 조용히 넓어질 수 없다.
+1 -1
View File
@@ -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 `com.hyeonworks.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. |
@@ -1,55 +0,0 @@
# gRPC advanced capability 지원 매트릭스
`:grpc-advanced:*`의 모든 capability, 그 등급, 그리고 등급을 올리는 데 필요한 것이다. 기본 등급의 정본은
`GrpcAdvancedCapability.defaultGrade`다. 근거가 있는 배포는 `GrpcAdvancedFeatureFlags.withGrade`로 바꾼다.
capability는 모두 기본으로 꺼져 있다. 스위치는 `app.grpc.advanced.<capability>.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를 올려도 다른 것의 등급은 바뀌지 않는다.
-74
View File
@@ -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에서 만들어지지 않고 정책으로 다스린다.
@@ -1,224 +0,0 @@
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다.
- 상태: 확인 안 함
- 작성일: 2026-08-30
- 요약: 타입 안전 gRPC 실행 플랫폼 계획을 이 저장소의 구조와 게이트에 맞춘 설계다.
- 현재 정본: `docs/compatibility/grpc-support-matrix.md`
<!-- 머리 블록 끝 -->
# 타입 안전 gRPC 실행 플랫폼 — 이 저장소 규약으로의 어댑팅 설계
두 계획 문서를 이 저장소(`ca-skeleton`)의 실제 구조·정책·빌드 게이트에 맞춰 실행 가능한 형태로
옮기는 설계다.
- 원본 A: `docs/2026-08-13-grpc-type-safe-rpc-platform-implementation-plan.md` (Stable, Task 1–53)
- 원본 B: `docs/2026-08-13-grpc-advanced-capabilities-expansion-plan.md` (Advanced, Task 1–18)
원본은 `modules/grpc/**` · Gradle Kotlin DSL · 패키지 `io.backend.skeleton.grpc` · Spring Boot 4.1을
전제한다. 이 저장소는 `src/**` · Groovy DSL · `dev.caskeleton` · Spring Boot 4.0.8 · fail-closed
module registry를 쓴다. 원본 Global Constraint의 마지막 항목이 이 어댑팅을 명시적으로 허용한다:
"실제 저장소 구조가 예상 경로와 다르면 파일 경로만 매핑하고 공개 계약·불변 조건·테스트 의미는
변경하지 않는다."
## 1. 패밀리 위치 — 왜 `adapter:inbound:grpc` 확장이 아닌가
원본이 기술하는 것은 인바운드 어댑터 하나가 아니라 **자기 API·SPI·adapter·조립 경계를 가진 벤더드
RPC 플랫폼**이다. 이 저장소에는 그 형태의 선례가 이미 있다 — `messaging:*`. root `CLAUDE.md`가
직접 그렇게 규정한다: "vendored messaging platform: a product with its own API, SPI, adapters and
composition boundary, not a layer of this application".
따라서 gRPC 플랫폼도 같은 자리에 둔다.
```text
src/grpc/ → :grpc:* Stable 플랫폼 (12 leaf)
src/grpc-advanced/ → :grpc-advanced:* Advanced/Experimental (6 leaf)
src/adapter/inbound/grpc 기존 인바운드 전송 어댑터 (그대로 유지)
```
`grpc-advanced`를 별도 디렉터리·별도 Gradle prefix로 分離하는 이유는 원본 Stable Task 1의 불변
조건 "Stable starter가 `modules/grpc-advanced`를 참조하면 build를 실패시킨다"를 registry의
`allowed_dependencies`만으로 기계 검증할 수 있게 만들기 위해서다. `verifyCleanArchitectureDependencies`가
그 게이트다.
패키지 루트는 `dev.caskeleton.grpc` / `dev.caskeleton.grpc.advanced`다.
## 2. Leaf 매핑 — 원본 31개 모듈 → 이 저장소 18개 leaf
원본 모듈 경계 중 **이 저장소가 이미 다른 메커니즘으로 표현하는 것**만 합친다. 능력(capability)은
하나도 버리지 않는다.
> **2026-09-28 변경(리뷰 후속 S7-#3·S7-#13, 소유자 결정 18).** 아래 두 표는 채택 당시의 leaf 구성이다.
> 현재는 `grpc-policy`·`grpc-server`·`grpc-client`·`grpc-discovery`·`grpc-admin` → `grpc-runtime`,
> `grpc-proto-contract`·`grpc-codegen` → `grpc-contract`(protobuf Gradle 플러그인 + CI의 Buf, D5/D6 폐기 —
> ADR-GRPC-002 superseded), `grpc-advanced-bootstrap`·`-edition`·`-streaming`·`-resilience`·`-diagnostics`
> → `grpc-advanced`로 합쳐졌다. `grpc-advanced-compat`은 그대로다. 패키지 이름은 바뀌지 않았다. 현재
> leaf 목록은 registry(`src/config/architecture/modules.json`)가 SSOT다.
### Stable — `src/grpc/`
| leaf | 원본 모듈 | 담는 Task | 의존 |
| --- | --- | --- | --- |
| `grpc-core-api` | grpc-core-api | 2–7 | (없음, Java stdlib) |
| `grpc-proto-contract` | grpc-proto-contract | 8 | core-api |
| `grpc-codegen` | grpc-codegen | 9–11 | core-api, proto-contract |
| `grpc-policy` | grpc-policy | 12, 16, 17, 20, 28–31, 33, 34, 37–43 | core-api |
| `grpc-server` | grpc-server | 13–15, 18, 19 | core-api, policy |
| `grpc-client` | grpc-client | 24–27 | core-api, policy |
| `grpc-discovery` | grpc-discovery | 35, 36 | core-api, client |
| `grpc-admin` | grpc-admin | 21–23, 45 | core-api, server |
| `grpc-observability` | grpc-observability | 44 | core-api |
| `grpc-operation-ledger-jpa` | grpc-operation-ledger-jpa | 32 | core-api |
| `grpc-spring-boot-starter` | grpc-spring-boot-starter | 52 | 위 전부 |
| `grpc-testkit` | testkit-core + -inprocess + -netty + -fault | 46–51, 53 | 위 전부 |
**testkit 4개를 1개로 합친 근거.** 원본이 testkit을 넷으로 쪼갠 목적은 "in-process 증거를 실제
네트워크 증거로 오인하지 않게 한다"이다. 이 저장소는 그 목적을 모듈 경계가 아니라 **strict test
lane** 컨벤션(`ca.strict-test-lane`)으로 이미 표현한다 — lane은 태그/소스셋/명시 테스트 중 하나로만
선택하고, 아무것도 실행하지 않으면 실패하며, up-to-date 결과를 제공하지 않는다. 그래서 네 모듈은
`grpc-testkit` 한 leaf 안의 네 lane이 된다:
`grpcInProcessContractTest`, `grpcNettyContractTest`, `grpcFaultTest`, `grpcPerformanceTest`.
원본의 "in-process는 HTTP/2·TLS 증거가 아니다"는 lane 분리와 `GrpcEvidenceGrade`로 강제한다.
### Advanced — `src/grpc-advanced/`
| leaf | 원본 모듈 | 담는 Task |
| --- | --- | --- |
| `grpc-advanced-bootstrap` | grpc-advanced-bootstrap | A1, A18 |
| `grpc-advanced-edition` | grpc-edition-2024 + grpc-edition-2026-experimental | A2, A3 |
| `grpc-advanced-streaming` | grpc-client-streaming + grpc-bidi-streaming + grpc-manual-flow-control | A4–A7 |
| `grpc-advanced-resilience` | grpc-hedging + grpc-custom-resolver + grpc-custom-load-balancer + grpc-xds | A8–A11 |
| `grpc-advanced-compat` | grpc-web + grpc-servlet-compat + grpc-integration-bridge + grpc-reactor + grpc-kotlin | A12–A16 |
| `grpc-advanced-diagnostics` | grpc-channel-diagnostics | A17 |
Advanced 모듈은 capability마다 leaf를 나누는 대신 **capability grade와 feature flag**
(`GrpcAdvancedCapability` / `GrpcAdvancedFeatureFlags`)로 분리한다. A18의 요구사항
"Edition, streaming, xDS, gRPC-Web, Servlet, language adapter가 서로의 승격을 묶지 않는다"는
leaf 경계가 아니라 capability별 독립 promotion evidence로 표현되므로, 합쳐도 그 불변 조건은 유지된다.
## 3. 원본과 달라지는 지점 (deviation)과 근거
| # | 원본 | 이 저장소 | 근거 |
| --- | --- | --- | --- |
| D1 | Spring Boot 4.1 BOM | Spring Boot 4.0.8 BOM | 저장소 실제 baseline(`src/build.gradle:13`). BOM이 SSOT라는 계약 자체는 유지 |
| D2 | Boot-managed Spring gRPC starter | self-managed `io.grpc` (`ext.grpcVersion`) | 기존 기록된 결정(`adapter/inbound/grpc/README.md` "왜 self-managed Netty 인가"). starter 커플링 회피 |
| D3 | Gradle Kotlin DSL, `settings.gradle.kts` | Groovy DSL + `config/architecture/modules.json` | registry가 leaf 목록의 SSOT이고 settings는 그것을 읽기만 한다 |
| D4 | `io.backend.skeleton.grpc` | `dev.caskeleton.grpc` | 저장소 기본 패키지 |
| D5 | Buf CLI (`bufLint`/`bufBreaking` 등) | 저장소 소유 규칙 엔진 + Gradle verify task | Buf CLI 바이너리가 이 환경에 없다. lint/format/breaking **규칙**을 Java로 구현해 동일 판정을 내리고, CLI는 동일 규칙을 재확인하는 선택 경로로 남긴다 |
| D6 | protoc/grpc-java codegen을 빌드에서 실행 | `.proto` 소스 + codegen **정책·descriptor 계약**만 실행, protoc 실행은 명시적 확장점 | 아래 별도 절 |
| D7 | `grpc-kotlin`의 `.kt` 소스 | Java 쪽 coroutine/Flow **경계 계약**만 | 저장소에 Kotlin 플러그인·소스셋이 없다. A16의 5개 요구사항 중 4개(스키마 단일 소스, cancellation 전파 계약, backpressure 우회 금지, evidence 타입 보존)는 Java 계약으로 표현 가능하고, Kotlin 툴체인 lane은 `GrpcKotlinCompatibilityGate`가 미충족으로 fail-closed 판정한다 |
| D8 | 새 leaf가 곧 런타임 | 신규 leaf 전부 `build: "optional-grpc"` (main runtime composition은 별도 Gradle edge로 결정) (build-only) | `messaging:*`가 처음 착지한 방식과 동일. 런타임 투입은 registry membership 변경 + `verifyRuntimeModuleMembership` 통과가 선행 조건이며, 그것은 별도 결정이다 |
### D6 — protoc 실행을 지금 켜지 않는 이유
이 저장소의 모든 leaf는 예외 없이 spotless(google-java-format) · checkstyle · spotbugs(HIGH) ·
errorprone · `-Werror`를 통과해야 한다(`src/build.gradle`의 `configure(subprojects)` 블록). protoc가
만든 소스는 그 어느 것도 통과하지 못하므로, 실제 codegen을 켜려면 해당 소스셋에서 다섯 게이트를
모두 끄는 carve-out이 필요하다. 저장소에 선례는 있다(`jmh` 소스셋). 하지만 그 carve-out은 Task
10 하나를 위해 품질 게이트를 여는 결정이고, 그 결정은 이 작업 범위 밖의 승인 사항이다.
그래서 Task 8–11의 **불변 조건**은 전부 실행 가능한 형태로 구현한다:
proto style 규칙 검증, 삭제 필드 `reserved` 이력 대조, Buf breaking category(`FILE`) 판정,
generated package와 hand-written package 겹침 금지, descriptor+schema hash 릴리스 아티팩트,
consumer fixture 실패 시 릴리스 차단. 빠지는 것은 protoc 프로세스 호출 하나이고,
`GrpcCodegenManifest`가 그 지점을 단일 owner로 고정한 채 비워둔다.
## 4. 유지되는 원본 불변 조건 (변경 없음)
- 실행 증거 3축(Transport/Business/Stream) 분리, `RESPONSE_HEADERS_SEEN` → `COMMIT_CONFIRMED` 자동 승격 금지
- `DEADLINE_EXCEEDED` mutation = `COMPLETION_UNKNOWN` 후보, `UNAVAILABLE`만으로 상태 변경 RPC 재호출 금지
- `NON_IDEMPOTENT`에 explicit retry·hedging 금지, explicit retry owner는 하나
- Stable Unary는 positive deadline 필수
- Server Streaming: bounded queue + single serialized writer, partial delivery 후 whole-call retry 금지
- Stable RPC 유형은 Unary·Server Streaming, Client/Bidi는 Advanced
- production reflection 기본 비활성, dev·stage·prod TLS 필수, trust-all 금지
- Stable resolver = Static·DNS, Stable LB = pick_first·round_robin
- metric tag에 raw metadata/payload/actor/tenant/object/stream/idempotency ID 금지
- Netty가 Stable certification transport, in-process는 network/TLS 증거가 아님
## 5. 애플리케이션이 이 패밀리에 도달하는 경로
`messaging:*`의 MSG-015(bridge 부재)를 반복하지 않는다. 계약상의 경로는
```text
application-owned port → adapter:inbound:grpc (typed service adapter) → :grpc:grpc-server SPI
```
이고, Stable Task 13/14가 그 경계를 소유한다(`GrpcApplicationBoundaryRules`,
`GrpcRawApiImportRule`, `GrpcServiceAdapter`). 플랫폼이 green이 된 뒤 마지막 단계에서
`adapter-inbound-grpc`의 `allowed_dependencies`에 `grpc-core-api`·`grpc-server`를 추가하고
브리지를 배선한다. 그 전까지 플랫폼은 self-contained build-only다.
## 6. 원본 파일 목록 대비 대조 (2026-08-31 감사)
두 계획이 `Files:` 절에 명시한 산출물 전체를 기계적으로 대조했다. 감사 스크립트는 각 Task의 파일
basename이 저장소에 존재하는지 확인한다(build 산출물 제외, 단 annotation processor가 생성하는
`spring-configuration-metadata.json`은 build 출력에서 확인).
```text
STABLE (Task 1–53) : present=250 missing=11
ADVANCED (Task 1–18) : present= 91 missing= 2
TOTAL : present=341 missing=13
```
잔여 13건은 전부 아래 편차로 설명된다. **행동이 빠진 것은 없다.**
### 6.1 ADR 파일명 (6건) — 저장소 명명 규약
계획은 `ADR-060` ~ `ADR-065` 연번을 쓴다. 이 저장소의 `docs/adr/`는 접두사 규약을 쓴다
(`ADR-WS-001`, `ADR-MONGO-004`, `ADR-WEB-ADV-003`). 내용은 1:1이다.
| 계획 | 이 저장소 |
| --- | --- |
| ADR-060 platform-boundary | `ADR-GRPC-001-platform-family-and-registry-shape.md` |
| ADR-061 execution-evidence | `ADR-GRPC-003-three-axis-execution-evidence.md` |
| ADR-062 retry-idempotency | `ADR-GRPC-004-retry-ownership-and-durable-idempotency.md` |
| ADR-063 streaming-resume | `ADR-GRPC-005-server-streaming-single-writer-and-resume.md` |
| ADR-064 discovery-kubernetes | `ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md` |
| ADR-065 advanced-promotion | `ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md` |
계획에 없던 `ADR-GRPC-002-schema-governance-without-protoc.md`가 추가로 있다 — D6 결정을 기록한다.
### 6.2 codegen convention plugin 3건 — D6
`io.backend.grpc-buf-conventions.gradle.kts`, `io.backend.grpc-codegen-conventions.gradle.kts`,
그 `.properties`. protoc를 실행하지 않으므로 실행할 convention plugin이 없다. 이들이 고정했을 결정은
`GrpcCodegenManifest`·`GrpcCodegenOutput`·`GrpcGeneratedPackagePolicy`가 Java로 강제하고,
`buf.yaml`·`buf.gen.yaml`·`buf.lock`이 CLI가 있는 환경에서 같은 판정을 내리도록 커밋되어 있다.
### 6.3 TLS 인증서 3건 — 런타임 생성으로 대체
`ca.crt`, `server.crt`, `client.crt`. 커밋된 인증서는 만료되고, 커밋된 개인키는 개인키다.
`GrpcTlsTestMaterial`이 JDK `keytool`로 fixture마다 PKCS12를 생성하고 `close()`가 지운다. Netty의
`SelfSignedCertificate`는 JDK 21에서 `sun.security.x509` 미export로 실패하므로 쓰지 않았다.
### 6.4 Kotlin 소스 1건 — D7
`GrpcCoroutineAdapter.kt`. 저장소에 Kotlin 툴체인이 없다. 계약 요구 4건은 Java로 검증하고
(`GrpcKotlinProfile`, `GrpcCoroutineContextBridge`), compile lane은
`GrpcKotlinCompatibilityGate.supportableHere()`가 `false`로 fail-closed다.
### 6.5 2026-08-31 감사에서 실제로 메꾼 것 (6건)
감사가 아니었으면 남았을 것들이다.
| 항목 | 조치 |
| --- | --- |
| `GrpcKubernetesProfileValidator` | 이름 있는 타입으로 분리. VIP+장기스트림, drain grace < reconnect budget 두 규칙 추가 |
| ADR-064 상당 (discovery/Kubernetes) | `ADR-GRPC-006` 작성 |
| xDS `bootstrap.json` | 테스트 리소스로 추가 + `GrpcXdsStartupGuard.bootstrapMismatches`가 실제로 대조 (namespace 불일치·비TLS control plane 검출) |
| `control-plane-snapshot.json` | 테스트 리소스로 추가 + redactor가 실제 모양의 데이터로 검증됨 |
| `DocumentClientFixture.java` + fixture `build.gradle.kts` | 추가. `GrpcConsumerFixture.fromJavaSource`가 fixture 소스에서 service·method·package 요구사항을 **역산**하므로 손으로 적은 목록이 아니다 |
| `buf.gen.yaml`, `buf.lock` | 추가 + proto contract 테스트가 내용을 검증 |
### 6.6 테스트 클래스 17건 — 감사 후 계획대로 분리
감사 시점에 leaf별로 통합돼 있던 테스트를 계획이 명시한 이름으로 분리했다. 분리 전에도 모든
타입이 실제로 검증되고 있었으나(통합 클래스가 해당 타입을 참조), 계획과의 추적성을 위해 나눴다:
`GrpcNettyVariantSelectorTest`, `GrpcReflectionPolicyTest`, `GrpcClientMetadataPolicyTest`,
`GrpcKubernetesProfileTest`, `GrpcEdition2026GuardTest`, `GrpcClientStreamPolicyTest`,
`GrpcClientMessageDeduplicatorTest`, `GrpcBidiSequenceTrackerTest`, `GrpcDemandControllerTest`,
`GrpcHedgingEligibilityTest`, `GrpcResolverSafetyPolicyTest`, `GrpcLoadBalancerSafetyPolicyTest`,
`GrpcXdsStartupGuardTest`, `GrpcWebCompatibilityGateTest`, `GrpcServletStartupValidatorTest`,
`GrpcIntegrationBridgePolicyTest`, `GrpcReactorContextBridgeTest`, `GrpcKotlinCompatibilityGateTest`.
@@ -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 실행 플랫폼 — 실행 계획과 실행 결과
+4 -8
View File
@@ -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).
+1 -2
View File
@@ -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개를 단언한다.
@@ -1,88 +0,0 @@
# Runbook: gRPC advanced capabilities
범위: `:grpc-advanced:*` family. 여기 있는 것은 모두 기본으로 꺼져 있고, 배포가 이름을 대기 전까지 꺼진 채로
있다. 지금 이 family의 어떤 것도 런타임 조립에 들어가지 않는다.
스위치는 `app.grpc.advanced.<capability>.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는 통과했지만 아무것도 증명하지 않았다.
-160
View File
@@ -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"`라 기본 조립에 들어가지 않는다.
+13
View File
@@ -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/adr/ADR-GRPC-001`~`006`·`ADR-GRPC-ADV-001`, `docs/compatibility/`(폴더째), `docs/runbooks/grpc-platform-operations.md`·`grpc-advanced-capabilities.md`, `docs/design/2026-08-30-grpc-platform-adaptation-design.md`. 새 자리는 grpc-library repo이고 같은 이름의 파일이 이력째 있다. 그 repo에서 Java 패키지는 `com.hyeonworks.grpc`, proto 패키지는 `hyeonworks.grpc.common.v1`이다 | 이 경로를 고친 서비스는 「수정 대 삭제」 충돌이 난다. `project(':grpc:…')`·`project(':grpc-advanced:…')`나 `-p platforms/optional-build`를 쓴 서비스는 빌드가 실패한다 | 쓰지 않았으면 삭제를 그대로 받는다. 썼으면 grpc-library 첫 버전(`1.0.0`, 소유자가 태그를 단 뒤)을 좌표 `com.hyeonworks.grpc:<모듈>:1.0.0`으로 받고(저장소 선언은 그 repo README 「받는 법」), import를 `dev.caskeleton.grpc` → `com.hyeonworks.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 새 버전과 영향
+1
View File
@@ -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. 이 폴더를 고칠 때
+1 -1
View File
@@ -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` |
+5 -4
View File
@@ -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」 |
+1 -1
View File
@@ -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. 문서와 코드 불일치
+5 -13
View File
@@ -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=<sha>` | 릴리스 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` |
@@ -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`) |
+39
View File
@@ -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) | `com.hyeonworks.grpc` | 없음(채택 전) | 없음. `adapter:inbound:grpc`는 `io.grpc`를 직접 쓴다. 채택은 별도 결정이다 |
| `messaging-library` | 메시징 제품 | `com.hyeonworks.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`로 더한다. `com.hyeonworks` group은 그 저장소에서만, 나머지는 Maven Central에서만 찾는다. 선언 예는 라이브러리 repo README 「받는 법」이다. 공개 owner라 읽기 토큰은 필요 없다.
+3 -2
View File
@@ -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`가 정본이다.
+1 -1
View File
@@ -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, 테스트 이미지)",
+1 -1
View File
@@ -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 <=
@@ -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/**'
}
}
@@ -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/**'
}
}
@@ -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 {
@@ -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).
*
* <p>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.
* <p>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 {
@@ -5,7 +5,7 @@ import java.util.Objects;
/**
* One migration script as the inspector sees it (design §32).
*
* <p>The gRPC ledger's lane in the optional build compiles this file with {@link
* <p>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}
@@ -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).
*
* <p>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.
* <p>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 {
+1 -6
View File
@@ -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.
@@ -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, 여유를 모두 더한 값 이상이다")
+1 -1
View File
@@ -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.
File diff suppressed because one or more lines are too long
-8
View File
@@ -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'
}
}
}
@@ -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.
*
* <p>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);
}
}
}
@@ -192,7 +192,7 @@ public record ModuleRegistry(List<Module> modules, File source) {
* <p>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<String> unregisteredBuildScripts(File gradleRoot) {
@@ -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<Project> {
@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<ModuleRegistry.Module> modules = registry.modulesForBuild(buildName);
List<ModuleRegistry.Module> modules = registry.modulesForBuild("main");
List<String> registryViolations = registryViolations(registry, modules);
var clean =
@@ -50,13 +49,8 @@ public final class ArchitecturePlugin implements Plugin<Project> {
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
@@ -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<Project> {
@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));
}
}
@@ -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<Project> {
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);
}
@@ -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<Project> {
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(
@@ -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<Settings> {
@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");
}
}
@@ -42,9 +42,10 @@ import org.gradle.api.execution.TaskExecutionGraph;
* WorkflowGradleInvocations} and {@code ShellScript} name the shapes).
* </ol>
*
* <p>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
* <p>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<Project> {
/**
* 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();
@@ -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 {
-84
View File
@@ -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"
}
]
}
+3 -38
View File
@@ -263,14 +263,12 @@
</Match>
<!-- CT group 2 — designed for extension. Exception hierarchy roots (HttpClientException,
JpaPersistenceException, RedisOperationException, FileserverException and the optional
gRPC build's GrpcPlatformException, which GrpcDeadlineExceededException extends, each have
JpaPersistenceException, RedisOperationException and FileserverException each have
subclasses), ClientRuntime (BlockingClientRuntime extends it) and the abstract
JpaRepositoryFragmentSupport, which service repository fragments extend. -->
<Match>
<Bug pattern="CT_CONSTRUCTOR_THROW"/>
<Or>
<Class name="dev.caskeleton.grpc.api.error.GrpcPlatformException"/>
<Class name="dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException"/>
<Class name="dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException"/>
<Class name="dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException"/>
@@ -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. -->
<Match>
<Bug pattern="REDOS"/>
<Or>
<And><Class name="dev.caskeleton.grpc.core.GrpcChannelProfileName"/><Method name="&lt;clinit&gt;"/></And>
<And><Class name="dev.caskeleton.grpc.core.GrpcServiceName"/><Method name="&lt;clinit&gt;"/></And>
<And><Class name="dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsSignatureVerifier"/><Method name="&lt;clinit&gt;"/></And>
<And><Class name="dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonPathName"/><Method name="&lt;clinit&gt;"/></And>
<And><Class name="dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortField"/><Method name="&lt;clinit&gt;"/></And>
@@ -304,31 +299,13 @@
</Or>
</Match>
<!-- FindSecBugs REDOS, the "x([class]*x)?" shape: GrpcMetadataKey.CANONICAL and
GrpcResolverSafetyPolicy.AUTHORITY. The only unbounded quantifier sits in a group that
repeats at most once, so a failing match gives back one character at a time from a single
star — n steps, not 2^n. Measured with java.util.regex on 1k/10k/100k-unit inputs built to
fail late ("a.a"... + "!"): time grows tenfold per tenfold input, 300k characters in under
7 ms. The metadata key is also capped at 64 characters before the pattern runs; the
resolver authority has no cap, and a linear match costs no more than reading the update. -->
<Match>
<Bug pattern="REDOS"/>
<Or>
<And><Class name="dev.caskeleton.grpc.api.context.GrpcMetadataKey"/><Method name="&lt;clinit&gt;"/></And>
<And><Class name="dev.caskeleton.grpc.advanced.discovery.GrpcResolverSafetyPolicy"/><Method name="&lt;clinit&gt;"/></And>
</Or>
</Match>
<!-- FindSecBugs UNSAFE_HASH_EQUALS asks for a constant-time compare so that timing cannot leak a
secret digest. None of these digests is a secret: content SHA-256 the uploader supplied or
can compute (ContentPublishVerification, MetadataPointerContentPublisher,
FinalizeUploadApplicationUseCase), an integrity digest of the record's own policy snapshot
(ObjectOperationRecord), idempotency request/response digests the caller's own replay
produces (PostgreSqlIdempotencyStore), and a configured worker identity used as a lease
owner (PosterImageUploadIntent), and the gRPC channel profile fingerprints that
GrpcPlatformSnapshotService.driftAgainstRelease compares between two snapshots it was
handed — a configuration hash, published in the snapshot itself, compared offline with no
caller to time it. A comparison that leaks what the caller already knows leaks nothing. -->
owner (PosterImageUploadIntent). A comparison that leaks what the caller already knows leaks nothing. -->
<Match>
<Bug pattern="UNSAFE_HASH_EQUALS"/>
<Or>
@@ -337,21 +314,9 @@
<And><Class name="dev.caskeleton.adapter.outbound.objectstorage.control.ObjectOperationRecord"/><Method name="&lt;init&gt;"/></And>
<And><Class name="dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlIdempotencyStore"/><Method name="~complete|replayVerdict"/></And>
<And><Class name="dev.caskeleton.application.fileserver.upload.FinalizeUploadApplicationUseCase"/><Method name="requireClientDigestMatches"/></And>
<And><Class name="dev.caskeleton.grpc.admin.GrpcPlatformSnapshotService"/><Method name="~lambda\$driftAgainstRelease\$\d+"/></And>
</Or>
</Match>
<!-- COMMAND_INJECTION: GrpcTlsTestMaterial.runKeytool starts the running JDK's own keytool
(java.home/bin) through ProcessBuilder with an argument list — no shell, so no argument is
parsed as a command. Its callers pass fixed flags, paths of a temporary directory the
fixture created, and the hostname a test names for its certificate. It lives in
grpc-testkit, which no production leaf depends on. -->
<Match>
<Bug pattern="COMMAND_INJECTION"/>
<Class name="dev.caskeleton.grpc.testkit.netty.GrpcTlsTestMaterial"/>
<Method name="runKeytool"/>
</Match>
<!-- SQL_INJECTION_JDBC: transition() and transitionWithNextAttempt() append a fixed WHERE clause
to a SET clause that every caller passes as a string literal from this class; every value
is a bound parameter. The method names are the lambdas javac generates inside them. -->
+3 -9
View File
@@ -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 com.hyeonworks.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" }
-88
View File
@@ -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.<capability>.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로 인용하는 것.
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
@@ -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'
}
@@ -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=
@@ -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.
*
* <p>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.
*
* <p>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<GrpcMetadataKey> headerAllowlist, Set<String> 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<GrpcMetadataKey, String> metadataFrom(Map<String, Object> messageHeaders) {
if (messageHeaders == null) {
throw new IllegalArgumentException("message headers must not be null");
}
Map<GrpcMetadataKey, String> 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.
*
* <p>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.
*
* <p>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;
}
}
@@ -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}.
*
* <p>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 <Q> the request payload type
*/
public final class GrpcIntegrationInboundGateway<Q> {
/** 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<Q> 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<String, Object> 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;
}
}
@@ -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.
*
* <p>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 <C> the request payload type
*/
public final class GrpcIntegrationOutboundGateway<C> {
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<GrpcMetadataKey, String> metadataFrom(Message<C> 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<C> 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;
}
}
@@ -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.
*
* <p>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.
*
* <p>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<Instant> 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();
}
});
}
}
@@ -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.
*
* <p>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<Instant> 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.
*
* <p>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();
}
});
}
}
@@ -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.
*
* <p>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<GrpcContextSnapshot> 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;
}
}
@@ -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}.
*
* <p>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.
*
* <p>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 <R> Mono<R> unary(
Supplier<R> 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 <R> Flux<R> serverStream(List<R> 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));
}
}
@@ -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.
*
* <p>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 <C> the application command type
* @param <R> the application result type
*/
public final class ReactiveGrpcServerAdapter<C, R> {
private final BiFunction<C, GrpcRequestContext, Mono<R>> useCase;
private final Scheduler blockingScheduler;
/** Binds an adapter to its use case and the scheduler blocking work runs on. */
public ReactiveGrpcServerAdapter(
BiFunction<C, GrpcRequestContext, Mono<R>> 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.
*
* <p>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<R> 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;
}
}
@@ -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.
*
* <p>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<String> 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);
}
}
@@ -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.
*
* <p>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<String> REQUIRED_EXPOSED_HEADERS = Set.of("grpc-status", "grpc-message");
private GrpcWebProxyContract() {}
/** The headers a proxy must expose. */
public static Set<String> 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<String> violations(
GrpcWebProfile profile, Set<String> exposedHeaders, Set<String> allowedOrigins) {
if (profile == null || exposedHeaders == null || allowedOrigins == null) {
throw new IllegalArgumentException("a proxy check needs the profile and both CORS sets");
}
List<String> 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);
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.grpc.advanced.web;
import dev.caskeleton.grpc.core.RpcType;
/**
* Which RPC shapes gRPC-Web can actually carry.
*
* <p>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");
}
}
}
@@ -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);
}
}
@@ -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<String> outbound =
new GrpcIntegrationOutboundGateway<>(policy());
Message<String> 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<String> inbound = new GrpcIntegrationInboundGateway<>(otherType);
assertThatThrownBy(() -> inbound.toMessage("payload", requestContext()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("converting by reflection");
Message<String> message = MessageBuilder.withPayload("payload").build();
GrpcIntegrationOutboundGateway<String> 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<String> inbound = new GrpcIntegrationInboundGateway<>(policy());
Message<String> 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();
}
}
@@ -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);
}
}
@@ -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<String> 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<String> 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<String> 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);
}
}
}
@@ -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 }
@@ -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')
}
@@ -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=
@@ -1,65 +0,0 @@
package dev.caskeleton.grpc.advanced.bootstrap;
/**
* Every capability the Stable platform deliberately excludes, and how ready each one is.
*
* <p>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;
}
}
@@ -1,42 +0,0 @@
package dev.caskeleton.grpc.advanced.bootstrap;
/**
* A capability was used without being enabled.
*
* <p>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;
}
}
@@ -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.
*
* <p>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<GrpcAdvancedCapability, Boolean> enabled =
new EnumMap<>(GrpcAdvancedCapability.class);
private final Map<GrpcAdvancedCapability, GrpcCapabilityGrade> grades =
new EnumMap<>(GrpcAdvancedCapability.class);
private final boolean production;
private final Set<GrpcAdvancedCapability> productionApprovals;
private GrpcAdvancedFeatureFlags(
boolean production, Set<GrpcAdvancedCapability> 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<GrpcAdvancedCapability> 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<GrpcAdvancedCapability> active() {
Set<GrpcAdvancedCapability> running = EnumSet.noneOf(GrpcAdvancedCapability.class);
for (GrpcAdvancedCapability capability : GrpcAdvancedCapability.values()) {
if (GrpcAdvancedModuleGuard.available(this, capability)) {
running.add(capability);
}
}
return Set.copyOf(running);
}
}
@@ -1,64 +0,0 @@
package dev.caskeleton.grpc.advanced.bootstrap;
/**
* The single gate every advanced capability passes through.
*
* <p>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");
}
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.grpc.advanced.bootstrap;
/**
* How much a capability has been established, and what that permits.
*
* <p>{@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;
}
}
@@ -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.
*
* <p>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<String> adminNetworks, Set<String> 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<String> 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);
}
}
@@ -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.
*
* <p>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<String> maskedSocketAddresses,
Map<String, String> 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");
});
}
}
@@ -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.
*
* <p>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.
*
* <p>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.
*
* <p>{@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:<digest>}. 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.
*
* <p>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.
*
* <p>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<String, String> redact(
Map<String, String> raw, java.util.Set<String> addressFields) {
if (raw == null || addressFields == null) {
throw new IllegalArgumentException("redaction needs the map and the address field set");
}
Map<String, String> redacted = new LinkedHashMap<>();
raw.forEach(
(key, value) -> {
if (forbiddenField(key)) {
return;
}
redacted.put(key, addressFields.contains(key) ? maskAddress(value) : value);
});
return Map.copyOf(redacted);
}
}
@@ -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.
*
* <p>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<GrpcResolverUpdate> listener;
private final AtomicReference<GrpcEndpointSnapshot> 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<GrpcResolverUpdate> 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<String> 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<String> 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<GrpcEndpointSnapshot> 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);
}
}
@@ -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.
*
* <p>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;
}
}
@@ -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.
*
* <p>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.
*
* <p>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<String> 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());
}
}
@@ -1,58 +0,0 @@
package dev.caskeleton.grpc.advanced.discovery;
import java.util.Optional;
/**
* Which endpoint a picker chose, or why it chose none.
*
* <p>{@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<GrpcEndpointCandidate> 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);
}
}
@@ -1,29 +0,0 @@
package dev.caskeleton.grpc.advanced.discovery;
import java.util.List;
/**
* Chooses one endpoint from the candidates the resolver supplied.
*
* <p>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<GrpcEndpointCandidate> 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()));
}
}
@@ -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.
*
* <p>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.
*
* <p>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<GrpcEndpointCandidate> candidates) {
if (candidates == null) {
throw new IllegalArgumentException("a candidate list is required");
}
List<GrpcEndpointCandidate> 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;
}
}
@@ -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.
*
* <p>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<String> 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<String> violations(
GrpcResolverUpdate update, GrpcEndpointSnapshot lastAccepted) {
if (update == null) {
throw new IllegalArgumentException("an update is required");
}
List<String> 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<String, ?> config, List<String> 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<Map<String, ?>> acceptedServiceConfig(
GrpcResolverUpdate update, GrpcEndpointSnapshot lastAccepted) {
return violations(update, lastAccepted).isEmpty() ? update.serviceConfig() : Optional.empty();
}
}
@@ -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.
*
* <p>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<Map<String, ?>> serviceConfig) {
/**
* Requires a snapshot and the Optional. The service config is the parsed JSON object, the same
* {@code Map<String, ?>} 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());
}
}
@@ -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.
*
* <p>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<String> optedInModules, Set<String> 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.
*
* <p>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;
}
}
@@ -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.
*
* <p>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;
}
}
@@ -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.
*
* <p>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<String> outstanding() {
List<String> 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();
}
}
@@ -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.
*
* <p>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<String, Boolean> 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<String> brokenToolchains() {
return sourceCompatibleByToolchain.entrySet().stream()
.filter(entry -> !entry.getValue())
.map(Map.Entry::getKey)
.collect(java.util.stream.Collectors.toUnmodifiableSet());
}
/** Every incompatibility, described. */
public List<String> incompatibilities() {
List<String> 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();
}
}
@@ -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.
*
* <p>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;
}
}
@@ -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.
*
* <p>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<String> 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);
});
}
}
@@ -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.
*
* <p>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);
}
}
@@ -1,49 +0,0 @@
package dev.caskeleton.grpc.advanced.resilience;
import java.time.Duration;
/**
* What a hedged call cost and what it saved.
*
* <p>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;
}
}

Some files were not shown because too many files have changed in this diff Show More