Files
grpc-library/grpc/CLAUDE.md
T
DongHyeonka cd4e117247 feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다
문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지
크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의
500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본
(TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR
테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로
만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져
객체 저장소 lane이 돌지 않았다.

방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은
결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD,
S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한).
MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자·
mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고,
scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과
왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와
결정은 리뷰 README 14절에 있다.

위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서
H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC·
WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체,
샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개
(composition:durable-operation, adapter:inbound:messaging)와 새
마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1,
grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면
실패한다(runbook에 확인 쿼리).

검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함
전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절
BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션
기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가,
샘플 Idempotency-Key 오류 코드 변경.
2026-11-03 19:52:06 +09:00

13 KiB

grpc — local authority for the gRPC platform family

이 문서는 grpc:* family의 local authority다. gRPC platform은 기본 application build와 분리된 src/optional-platforms build가 소유한다. 여기서 정하는 것은 family별 framework 규칙, 증거 등급, Stable 범위의 경계와 application에 채택될 때 필요한 계약이다.

Root 정책(CLAUDE.md / AGENTS.md)과 충돌하면 root가 이긴다.

이 family는 Clean Architecture의 계층이 아니라 벤더드 RPC 플랫폼이다 — messaging:*와 같은 자리에 있고 같은 이유로 있다. 자기 API(port)와 adapter와 조립 경계(starter)를 가지며, 애플리케이션은 adapter:inbound:grpc를 통해 라이브러리로서 도달한다.

설계 근거와 원본 계획 대비 deviation은 docs/superpowers/specs/2026-08-30-grpc-platform-adaptation-design.md가 SSOT다.

Family와 framework 규칙

leaf의 정확한 id는 registry에서 읽는다.

Family 역할 허용 framework
grpc-core-api 식별자, method policy, 실행 증거, 실패 모델, deadline, request context, operation ledger port Java stdlib만. io.grpc / Spring / protobuf / DB 타입 금지
grpc-contract .proto 스키마 소스(src/main/proto)와 protoc 생성 message. lint/breaking은 Buf(buf.yaml, CI job grpc-proto-buf) protobuf-java(생성 코드 runtime)만. 규칙을 Java로 재구현하지 않는다
grpc-runtime policy(validation, context, status/rich error, TLS/credential, deadline/cancellation, retry, idempotency, streaming, size/compression) · server(typed service adapter SPI, interceptor 순서, Netty profile) · client(named channel, runtime generation, typed stub factory) · discovery(Static/DNS, pick_first/round_robin, Kubernetes routing) · admin(health, reflection, drain, policy snapshot) io.grpc:grpc-api, grpc-stub. Spring·Netty 자체 금지 — Netty profile은 설정 모델이다
grpc-observability bounded metric/trace convention io.micrometer:micrometer-core만
grpc-operation-ledger-jpa mutation idempotency의 durable 저장 jakarta.persistence, spring-data-jpa. port는 core-api에 있다
grpc-spring-boot-starter 조립 경계, typed properties, startup validator Spring Boot autoconfigure. 여기서만
grpc-testkit in-process / 실제 Netty / fault / performance 인증 io.grpc netty-shaded, inprocess. production leaf가 의존하지 않는다

grpc-core-api가 io.grpc를 이름조차 부르지 않는다는 것이 이 family의 핵심 제약이다. 실행 증거와 실패 모델은 "전송이 무엇을 했는가"를 기술하는 계약이고, 그 계약 안에 전송 타입이 들어가면 계약이 전송의 일부가 된다. GrpcStatusCode가 io.grpc의 코드를 미러링하는 이유가 이것이고, 양방향 번역은 grpc-runtime의 GrpcStatusMapping이 단독으로 소유한다.

기본 전송 한도(메시지 1 MiB, metadata 8 KiB)는 grpc-core-api의 GrpcTransportLimits 한 곳에 있고, server profile·named channel profile·method size profile·method policy 기본값·metadata budget이 모두 그 상수를 쓴다. GrpcPlatformStartupValidator는 method의 inbound 한도가 server profile 한도보다 크면 기동을 거부한다.

.proto의 proto 조직 이름은 caskeleton이다(package caskeleton.grpc.common.v1, 생성 Java 패키지 caskeleton.grpc.common.v1.generated — 손으로 쓴 dev.caskeleton과 겹치지 않는다). 템플릿을 재사용할 때 바꾸는 방법은 AGENTS.md 「템플릿 재사용 체크리스트」에 있다.

증거 등급 — testkit이 하나의 leaf인 이유

원본 계획은 testkit을 core/in-process/netty/fault 4개 모듈로 쪼갠다. 목적은 "in-process 결과를 네트워크 증거로 오해하지 않게 한다"이고, 이 저장소는 그 목적을 모듈 경계가 아니라 strict test lane으로 표현한다(ca.strict-test-lane: lane은 아무것도 실행하지 않으면 실패하고 up-to-date 결과를 제공하지 않는다).

grpc-testkit의 네 lane과 그 태그:

lane 태그 증명하는 것
grpcInProcessContractTest grpc-inprocess adapter, interceptor 순서, status, validation, idempotency replay
grpcNettyContractTest grpc-netty 실제 소켓 위의 HTTP/2, TLS/mTLS, metadata·message hard limit, GOAWAY, drain
grpcFaultTest grpc-fault 각 증거 경계에서의 연결 손실, completion unknown, partial stream
grpcPerformanceTest grpc-performance latency percentile, saturation, drain budget

lane 분리만으로는 리포트가 잘못된 run을 인용하는 것을 막지 못하므로 GrpcEvidenceGrade가 런타임 체크로 이를 붙든다: CONTRACT 등급으로 tls를 주장하면 예외다.

performance lane은 기본 test에서 제외된다(leaf build.gradle). 공유 CI runner에서의 측정은 release path의 flaky gate가 되고, flaky gate는 꺼진다.

Stable 범위

Stable RPC 유형은 Unary와 Server Streaming뿐이다. Client Streaming, Bidirectional Streaming, hedging, xDS, custom resolver/LB, gRPC-Web, Servlet, Reactor, Kotlin은 전부 grpc-advanced:*이며 capability flag 뒤에 있다. GrpcPlatformStartupValidator가 Stable catalog에 streaming method가 등록되면 startup을 거부한다.

grpc-spring-boot-starter는 어떤 advanced module도 참조하지 않는다. registry의 allowed_dependencies와 verifyCleanArchitectureDependencies가 이를 build time에 강제한다.

Optional build에 있다는 것의 의미

grpc:*와 grpc-advanced:*는 기본 ca-skeleton settings에 include되지 않는다. 따라서 일반 :app-bootstrap:build는 이 project들을 configure하지 않는다(목록은 registry의 "build": "optional-grpc"). 플랫폼 자체는 ./gradlew -p optional-platforms ci로 검증하고, application runtime에 실제 채택하려면 composition root가 명시적으로 dependency를 가져오는 별도 변경이 필요하다.

런타임 포함 여부와 qualification은 별개다. in-process·Netty·fault lane이 통과해도 실제 배포 환경의 soak/performance baseline을 자동으로 의미하지 않는다. 지원 범위는 release gate와 support matrix가 별도로 정의한다.

application이 이 family에 도달하는 경로

messaging:*의 MSG-015(bridge 부재)를 반복하지 않는 것이 이 family의 목표다. 계약상의 경로는

application-owned port → adapter:inbound:grpc (typed service adapter) → :grpc:grpc-runtime SPI

이고 GrpcServiceAdapter가 그 SPI를 소유한다. inbound adapter가 outbound adapter·persistence에 직접 닿지 않는 규칙은 app-bootstrap ArchUnit(INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS)이 검사한다. 현재 adapter:inbound:grpc는 이 family에 의존하지 않는다 — registry의 allowed_dependencies를 보라. 배선은 별도 결정이며, 그때 registry edge와 브리지가 함께 들어간다. starter가 operation-ledger-enabled=true일 때 멱등성 판단 bean을 조립하는 것(03-11)은 이 배선이 아니다 — starter는 서버를 만들지 않고, 그 bean을 서버에 붙이는 일은 채택하는 쪽의 몫이다(아래 「Durable operation ledger adoption」).

테스트 명령

focused test는 registry의 gradle_path에서 파생한다.

cd src
./gradlew -p optional-platforms :grpc:<leaf>:test --console=plain
./gradlew -p optional-platforms :grpc:grpc-testkit:grpcInProcessContractTest --console=plain
./gradlew -p optional-platforms :grpc:grpc-testkit:grpcNettyContractTest --console=plain
./gradlew -p optional-platforms :grpc:grpc-testkit:grpcFaultTest --console=plain
./gradlew -p optional-platforms :grpc:grpc-testkit:grpcPerformanceTest --console=plain

금지

  • grpc-core-api에서 io.grpc / Spring / protobuf / JPA 타입 사용.
  • Stable leaf에서 :grpc-advanced:* 참조.
  • grpc-testkit을 production leaf가 의존하는 것.
  • in-process 결과로 transport capability를 주장하는 것 (GrpcEvidenceGrade가 거부한다).
  • metric tag에 raw metadata·payload·actor/tenant/object/stream/idempotency 식별자를 넣는 것 (GrpcMetricCardinalityPolicy가 거부한다).

Adoption-time observability gate

The metric names implemented by grpc-observability are not registered in docs/registries/metrics.yaml yet because this optional family is not a shipped runtime capability. Do not present those names as repository-certified metrics until adoption adds registry entries with the repository's .seconds / .total unit naming and the corresponding validation gate.

Durable operation ledger adoption

grpc-spring-boot-starter does not pull the JPA ledger adapter transitively (11-M9). A deployment that needs durable operation idempotency adds :grpc:grpc-operation-ledger-jpa explicitly, defines a GrpcOperationLedger bean (new JpaGrpcOperationLedger(repository)), includes that adapter's Flyway location db/migration/grpc (V001 table, V002 retention index), and sets the flag below. A deployment that does not adopt the ledger pays no Spring Data JPA classpath cost.

Key (app.grpc.platform.*) Default What it does
operation-ledger-enabled false true: the starter assembles GrpcIdempotencyInterceptor (bean grpcIdempotencyInterceptor) and GrpcOperationLedgerRetention (bean grpcOperationLedgerRetention) over the deployment's GrpcOperationLedger bean, and refuses startup when there is none. false: neither bean exists, and a method that is IDEMPOTENCY_KEY_REQUIRED refuses startup
operation-ledger-claim-ttl 5m How long an IN_PROGRESS claim is trusted to have a live owner. After it, a retry of the same request takes the claim over (GrpcOperationLedger.reclaimStale). Refused at startup unless longer than every keyed method's deadline
operation-ledger-retention 24h How long a finished (COMMITTED/FAILED_TERMINAL) record is kept before GrpcOperationLedgerRetention.purgeExpired may delete it. IN_PROGRESS rows are never purged

Defaults: the 5-minute TTL is the value the ledger contract and interceptor tests certify, far beyond a unary deadline, and short enough that a key whose owner died unblocks within a client's retry patience. The 24-hour retention matches the HTTP idempotency replay TTL (app.capabilities.idempotency.replay-ttl). A retry of a key after its record was purged is a new operation, so the retention must exceed the callers' retry window.

These keys are not in docs/registries/env-keys.yaml: no app.grpc.platform.* key is, because the optional build is not part of the shipped runtime. They join the registry when a composition root adopts the platform.

Why the starter assembles the interceptor (03-11 (b)), and not (a). The review proposed (a): delete the flag and judge by whether a ledger bean exists. The owner chose (b): the flag stays and means what it says — when true, the decision function is assembled and its TTL comes from configuration. (a) would have removed the false promise but left every adopter to rebuild the same assembly and TTL validation by hand; (b) keeps that in one place. The interceptor bean has no @ConditionalOnMissingBean on purpose: a replacement would silently ignore operation-ledger-claim-ttl. Duplicates of a running operation are refused (REJECT_IN_PROGRESS), not told to wait; a wait-and-poll option becomes a key when a keyed method needs it.

Server wiring is still the adopter's, and stays a separate decision. The starter builds no server, so assembling the decision does not wire the platform into adapter:inbound:grpc (see "배선은 별도 결정" above). GrpcIdempotencyInterceptor is a decision function, not an io.grpc.ServerInterceptor. The adopter injects the bean by type and calls it from its own IDEMPOTENCY stage interceptor (GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)) or from its typed service adapter: decide(...) before the mutation, recordCommit(...) inside the mutation's transaction, recordFailure(...) on a terminal failure.

Purge scheduling is the adopter's. GrpcOperationLedgerRetention.purgeExpired(now) deletes expired finished rows in bounded batches (500 per statement) until a batch comes back short. The starter does not schedule it: it owns no scheduler and cannot know which replica should run it, and a scheduled bean would force a task scheduler onto every deployment. The adopter calls it from its own scheduler (for example hourly); concurrent runs on several replicas are safe because the delete skips locked rows. Running it never is safe but lets the table grow without bound.

The commit must be recorded in the mutation's transaction and the TTL must be longer than the slowest keyed method; both reasons are in ADR-GRPC-004.