refactor(repo)!: 들여온 플랫폼을 src/platforms 아래로 묶는다

문제: src/ 최상위에 계층 폴더와 들여온 제품 폴더(messaging, grpc,
grpc-advanced)와 optional 빌드 폴더(optional-platforms)가 같은 높이로
놓여, 무엇이 이 애플리케이션의 계층인지 폴더만으로 안 보인다.
src/config/에는 빌드 전체 설정과 기능 하나가 주인인 데이터(jpa,
messaging, mongodb)가 섞여 있다.

고른 방법(소유자 결정 2026-11-07, 설계 가-1):
- git mv로 src/platforms/{messaging,grpc,grpc-advanced,optional-build}.
  registry source_path 28행만 바꾸고 Gradle 경로(:messaging:*, :grpc:*)는
  그대로다. optional 빌드의 이름(optional-platforms)도 그대로다.
- optional 빌드가 한 단계 깊어져, build-logic이 "optional 빌드의 부모 =
  주 빌드"로 가정한 네 곳(registry settings, ArchitecturePlugin, 테스트
  이미지 catalog, checkstyle·spotbugs 설정)을 MainBuild(위로 올라가며
  registry·설정 파일을 찾음)로 바꾼다.
- settings.gradle·build.gradle의 상대 경로, workflow의 -p 값과 경로,
  buf 작업 폴더를 고친다. buf breaking은 이동 전 baseline에서도 옛
  경로로 비교해 이동 PR에서 건너뛰지 않는다.
- config/jpa, config/messaging, config/mongodb의 데이터를 주인 leaf의
  release/로 옮기고 읽는 빌드 줄·테스트·스크립트·문서를 고친다.
- 루트 CLAUDE.md 5절에 최상위 폴더 지도를 한 줄로 적는다.
버린 대안: Gradle 루트를 저장소 루트로(가-3, CI 재편 때 다시 봄),
application-* 묶기(가-2, 파생 서비스 충돌이 큼).

위험·한계: Gradle 문서의 "이름 = 위치" 권고와 한 단계 어긋난다
(:messaging:x가 platforms/messaging/x). 옮긴 폴더를 고쳐 쓰던 파생
서비스는 이름 바뀜 충돌이 날 수 있다(B-52). docs/capability-status.md
「제거된 코드」 표와 docs/work/evidence.md의 옛 경로는 이력이라 두었다.

검증(desktop, 트리 2b3354a4, ~/t1-layout-logs/):
- ./gradlew :ci :verifyDependencyLocks --warning-mode=fail --continue
  첫 실행 rc=1: MessagingAuthorityContractTest가 src/messaging을 찾아 실패
  → 경로를 고침. 두 번째 rc=1: messaging-policy
  MessagingAdmissionControllerTest.aWaitingCallerIsAdmittedOnceAPermitIsReturned
  (2초 대기 경쟁, 부하 7.3에서 한 번 실패, 코드 변경 없는 leaf) → --rerun
  3회 모두 통과. 세 번째 rc=0
- -p platforms/optional-build ci rc=0, 두 빌드의 verifyStrictLaneStages
  --dry-run rc=0, -p build-logic check rc=0
- :app-bootstrap:documentContractTest
  :adapter:outbound:persistence-mongo:mongoDocumentContractTest rc=0
- ./gradlew projects(주 빌드)와 optional 빌드 projects의 프로젝트 목록이
  이동 전 트리와 같다(Gradle 경로 불변)
- check-work-docs.py, 상대 링크 검사 rc=0

Refs: design-docs repo-structure/README.md 3.1, repo-structure/01-backend-layout.md 6.1
BREAKING CHANGE: src/messaging·src/grpc·src/grpc-advanced·src/optional-platforms가 src/platforms/ 아래로, src/config/{jpa,messaging,mongodb}가 주인 leaf의 release/로 옮겨졌다. optional 빌드는 -p platforms/optional-build로 부른다. docs/upgrade/2026-11-maturity-review.md B-52.
This commit is contained in:
DongHyeonka
2026-11-07 13:04:54 +09:00
parent 50cd7154d0
commit 8d69e599a3
850 changed files with 271 additions and 180 deletions
+88
View File
@@ -0,0 +1,88 @@
# grpc-advanced — local authority for the advanced gRPC capabilities
이 문서는 `grpc-advanced:*` family의 **local authority**다. leaf 목록·gradle path·허용 의존성은
`src/config/architecture/modules.json`이 SSOT다. Root 정책(`CLAUDE.md` / `AGENTS.md`)과 충돌하면
root가 이긴다.
이 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/CLAUDE.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로 인용하는 것.
@@ -0,0 +1,24 @@
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'
}
@@ -0,0 +1,104 @@
# 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.28.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.2.1-android=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
com.google.j2objc:j2objc-annotations:3.0.0=compileClasspath,testCompileClasspath
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
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.68.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.grpc:grpc-stub:1.68.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.projectreactor:reactor-core:3.8.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.commons:commons-text:1.3=checkstyle
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.checkerframework:checker-qual:3.42.0=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.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,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.18=spotbugs,spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.integration:spring-integration-core:7.0.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-messaging:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
empty=
@@ -0,0 +1,78 @@
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;
}
}
@@ -0,0 +1,58 @@
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;
}
}
@@ -0,0 +1,57 @@
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;
}
}
@@ -0,0 +1,60 @@
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();
}
});
}
}
@@ -0,0 +1,61 @@
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();
}
});
}
}
@@ -0,0 +1,58 @@
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;
}
}
@@ -0,0 +1,57 @@
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));
}
}
@@ -0,0 +1,57 @@
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;
}
}
@@ -0,0 +1,62 @@
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);
}
}
@@ -0,0 +1,64 @@
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);
}
}
@@ -0,0 +1,38 @@
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");
}
}
}
@@ -0,0 +1,47 @@
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);
}
}
@@ -0,0 +1,112 @@
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();
}
}
@@ -0,0 +1,108 @@
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);
}
}
@@ -0,0 +1,180 @@
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);
}
}
}
@@ -0,0 +1,80 @@
# 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 }
@@ -0,0 +1,28 @@
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')
}
@@ -0,0 +1,91 @@
# 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.28.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.2.1-android=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
com.google.j2objc:j2objc-annotations:3.0.0=compileClasspath,testCompileClasspath
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
io.grpc:grpc-api:1.68.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.grpc:grpc-stub:1.68.1=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.checkerframework:checker-qual:3.42.0=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.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.mockito:mockito-core:5.20.0=mockitoAgent
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
empty=
@@ -0,0 +1,65 @@
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;
}
}
@@ -0,0 +1,42 @@
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;
}
}
@@ -0,0 +1,105 @@
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);
}
}
@@ -0,0 +1,64 @@
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");
}
}
}
@@ -0,0 +1,38 @@
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;
}
}
@@ -0,0 +1,55 @@
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);
}
}
@@ -0,0 +1,63 @@
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");
});
}
}
@@ -0,0 +1,107 @@
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);
}
}
@@ -0,0 +1,75 @@
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);
}
}
@@ -0,0 +1,36 @@
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;
}
}
@@ -0,0 +1,46 @@
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());
}
}
@@ -0,0 +1,58 @@
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);
}
}
@@ -0,0 +1,29 @@
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()));
}
}
@@ -0,0 +1,76 @@
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;
}
}
@@ -0,0 +1,100 @@
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();
}
}
@@ -0,0 +1,43 @@
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());
}
}
@@ -0,0 +1,47 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,70 @@
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();
}
}
@@ -0,0 +1,72 @@
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();
}
}
@@ -0,0 +1,70 @@
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;
}
}
@@ -0,0 +1,72 @@
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);
});
}
}
@@ -0,0 +1,51 @@
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);
}
}
@@ -0,0 +1,49 @@
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;
}
}
@@ -0,0 +1,61 @@
package dev.caskeleton.grpc.advanced.streaming;
/**
* One direction of a bidirectional stream, tracked on its own.
*
* <p>Independently, because the two directions genuinely end at different times: a client that has
* finished sending is still receiving, and a server that has finished sending is still reading. A
* single state for both cannot express either, and the usual symptom is a stream closed while one
* side still had messages to deliver.
*/
public record GrpcBidiDirectionState(long lastSequence, boolean halfClosed, boolean cancelled) {
/** Requires a non-negative position. */
public GrpcBidiDirectionState {
if (lastSequence < 0) {
throw new IllegalArgumentException("a direction's sequence is at or after zero");
}
if (halfClosed && cancelled) {
throw new IllegalArgumentException(
"a direction that was cancelled did not half-close; the two are different endings and a "
+ "client acts on them differently");
}
}
/** A direction that has sent nothing yet. */
public static GrpcBidiDirectionState open() {
return new GrpcBidiDirectionState(0L, false, false);
}
/**
* Records a message at the next sequence.
*
* @throws IllegalStateException when the direction has already ended
*/
public GrpcBidiDirectionState advanced() {
if (halfClosed || cancelled) {
throw new IllegalStateException(
"this direction has already ended; a message after half-close is a protocol error, not a "
+ "late arrival");
}
return new GrpcBidiDirectionState(lastSequence + 1, false, false);
}
/** Records that this direction will send nothing more. */
public GrpcBidiDirectionState halfClose() {
if (cancelled) {
throw new IllegalStateException("a cancelled direction cannot half-close");
}
return new GrpcBidiDirectionState(lastSequence, true, false);
}
/** Records that this direction was cancelled. */
public GrpcBidiDirectionState cancel() {
return new GrpcBidiDirectionState(lastSequence, false, true);
}
/** Whether this direction has finished. */
public boolean ended() {
return halfClosed || cancelled;
}
}
@@ -0,0 +1,42 @@
package dev.caskeleton.grpc.advanced.streaming;
/**
* What a bidirectional resume has to carry: both applied positions, and the generation they belong
* to.
*
* <p>Both, because a resume that restores one direction and restarts the other produces exactly the
* failure the dual sequence exists to prevent. The generation is checked first: a mismatch means
* the session was restarted rather than resumed, and continuing from either position would be
* meaningless.
*/
public record GrpcBidiResumeState(
GrpcClientStreamSessionId sessionId, long clientAppliedSequence, long serverAppliedSequence) {
/** Requires a session and two non-negative positions. */
public GrpcBidiResumeState {
if (sessionId == null) {
throw new IllegalArgumentException("a bidi resume state belongs to a session");
}
if (clientAppliedSequence < 0 || serverAppliedSequence < 0) {
throw new IllegalArgumentException("applied sequences are at or after zero");
}
}
/**
* Whether {@code presented} can continue this session.
*
* <p>A generation mismatch requires a full restart. The session was re-established rather than
* resumed, so neither side's position refers to the same stream of messages.
*/
public boolean resumableFrom(GrpcClientStreamSessionId presented) {
return presented != null
&& sessionId.sameSessionAs(presented)
&& presented.generation() == sessionId.generation();
}
/** The state after a resume, at the next generation. */
public GrpcBidiResumeState resumed() {
return new GrpcBidiResumeState(
sessionId.resumed(), clientAppliedSequence, serverAppliedSequence);
}
}
@@ -0,0 +1,62 @@
package dev.caskeleton.grpc.advanced.streaming;
/**
* Two sequences, one per direction, never merged.
*
* <p>Merging them is the mistake this class exists to prevent, and it is tempting because one
* counter looks simpler. It is not equivalent: the client's message 5 and the server's message 5
* are unrelated events, and a shared counter makes a resume token from one side meaningless to the
* other — so a reconnect either skips or replays, depending on which side moved faster.
*/
public final class GrpcBidiSequenceTracker {
private GrpcBidiDirectionState clientToServer = GrpcBidiDirectionState.open();
private GrpcBidiDirectionState serverToClient = GrpcBidiDirectionState.open();
/** Records a client-to-server message and returns its sequence. */
public synchronized long nextClientSequence() {
clientToServer = clientToServer.advanced();
return clientToServer.lastSequence();
}
/** Records a server-to-client message and returns its sequence. */
public synchronized long nextServerSequence() {
serverToClient = serverToClient.advanced();
return serverToClient.lastSequence();
}
/** The client-to-server direction. */
public synchronized GrpcBidiDirectionState clientToServer() {
return clientToServer;
}
/** The server-to-client direction. */
public synchronized GrpcBidiDirectionState serverToClient() {
return serverToClient;
}
/** Records that the client will send nothing more. */
public synchronized void halfCloseClient() {
clientToServer = clientToServer.halfClose();
}
/** Records that the server will send nothing more. */
public synchronized void halfCloseServer() {
serverToClient = serverToClient.halfClose();
}
/** Cancels one direction without touching the other. */
public synchronized void cancelClient() {
clientToServer = clientToServer.cancel();
}
/** Cancels the server direction without touching the client's. */
public synchronized void cancelServer() {
serverToClient = serverToClient.cancel();
}
/** Whether both directions have ended. */
public synchronized boolean bothEnded() {
return clientToServer.ended() && serverToClient.ended();
}
}
@@ -0,0 +1,77 @@
package dev.caskeleton.grpc.advanced.streaming;
import dev.caskeleton.grpc.streaming.GrpcFlowControlPolicy;
import java.util.Optional;
/**
* A bidirectional session: two directions, two queues, two single writers.
*
* <p>Two of everything, because the two directions have independent producers and independent
* consumers. Sharing a queue between them means the slower direction throttles the faster one; and
* sharing a writer reintroduces the concurrent-{@code onNext} problem the Stable serialized writer
* exists to solve, this time with the two sides of the same call racing each other.
*/
public final class GrpcBidiSession {
private final GrpcClientStreamSessionId sessionId;
private final GrpcBidiSequenceTracker sequences = new GrpcBidiSequenceTracker();
private final GrpcFlowControlPolicy inboundFlowControl;
private final GrpcFlowControlPolicy outboundFlowControl;
/** Opens a session with an independent flow-control policy per direction. */
public GrpcBidiSession(
GrpcClientStreamSessionId sessionId,
GrpcFlowControlPolicy inboundFlowControl,
GrpcFlowControlPolicy outboundFlowControl) {
if (sessionId == null || inboundFlowControl == null || outboundFlowControl == null) {
throw new IllegalArgumentException(
"a bidi session needs an id and a flow-control policy for each direction");
}
this.sessionId = sessionId;
this.inboundFlowControl = inboundFlowControl;
this.outboundFlowControl = outboundFlowControl;
}
/** The session's identity. */
public GrpcClientStreamSessionId sessionId() {
return sessionId;
}
/** The sequence tracker. */
public GrpcBidiSequenceTracker sequences() {
return sequences;
}
/** The inbound direction's bounds. */
public GrpcFlowControlPolicy inboundFlowControl() {
return inboundFlowControl;
}
/** The outbound direction's bounds. */
public GrpcFlowControlPolicy outboundFlowControl() {
return outboundFlowControl;
}
/** The resume state as it stands. */
public GrpcBidiResumeState resumeState() {
return new GrpcBidiResumeState(
sessionId,
sequences.clientToServer().lastSequence(),
sequences.serverToClient().lastSequence());
}
/**
* Whether {@code presented} may continue this session, and from where.
*
* @return empty when the generation does not match, which requires a full session restart
*/
public Optional<GrpcBidiResumeState> resumeFrom(GrpcClientStreamSessionId presented) {
GrpcBidiResumeState state = resumeState();
return state.resumableFrom(presented) ? Optional.of(state) : Optional.empty();
}
/** Whether the session is finished in both directions. */
public boolean complete() {
return sequences.bothEnded();
}
}
@@ -0,0 +1,123 @@
package dev.caskeleton.grpc.advanced.streaming;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Decides what to do with a client stream message that may have arrived before.
*
* <p>Checkpoint-based rather than a set of seen keys. A set grows without bound for the life of a
* session and answers "have I seen this" — which is not quite the question. The question is "has
* this been applied", and a monotonic applied-sequence answers it in constant space and survives
* the process restart that a set does not.
*
* <p>Replayed outcomes are kept for the small window after the checkpoint, so a duplicate that
* arrives before the checkpoint advances gets the original answer rather than being reapplied.
*/
public final class GrpcClientMessageDeduplicator {
private final ConcurrentMap<String, GrpcClientStreamCheckpoint> checkpoints =
new ConcurrentHashMap<>();
private final ConcurrentMap<String, String> replayableOutcomes = new ConcurrentHashMap<>();
/** What to do with an incoming message. */
public enum Disposition {
/** Not seen; apply it. */
APPLY,
/** Already applied; return the stored outcome if there is one, otherwise ignore. */
REPLAY,
/** Out of order ahead of the checkpoint; the sender skipped something. */
GAP
}
/** Starts tracking a session. */
public void beginSession(GrpcClientStreamSessionId sessionId, Instant at) {
if (sessionId == null || at == null) {
throw new IllegalArgumentException("a session needs an id and a moment");
}
checkpoints.putIfAbsent(sessionId.value(), GrpcClientStreamCheckpoint.empty(sessionId, at));
}
/**
* What to do with {@code message}.
*
* @throws IllegalStateException when the session is not being tracked, which means a message
* arrived for a session the server never opened
*/
public Disposition dispositionOf(GrpcClientStreamMessage<?> message) {
if (message == null) {
throw new IllegalArgumentException("a message is required");
}
GrpcClientStreamCheckpoint checkpoint = requireCheckpoint(message.sessionId());
if (checkpoint.alreadyApplied(message.sequence())) {
return Disposition.REPLAY;
}
if (message.sequence() > checkpoint.lastAppliedSequence() + 1) {
return Disposition.GAP;
}
return Disposition.APPLY;
}
/**
* Records that a message was applied, together with the outcome a duplicate would receive.
*
* <p>The application effect and this checkpoint belong in one transaction wherever the datastore
* allows it. Committing them separately leaves a window in which the effect is durable and the
* checkpoint is not, and a reconnect in that window reapplies the message.
*/
public void recordApplied(
GrpcClientStreamMessage<?> message, String outcomeReference, Instant at) {
GrpcClientStreamCheckpoint checkpoint = requireCheckpoint(message.sessionId());
checkpoints.put(message.sessionId().value(), checkpoint.advancedTo(message.sequence(), at));
if (outcomeReference != null && !outcomeReference.isBlank()) {
replayableOutcomes.put(message.dedupKey(), outcomeReference);
}
}
/** The stored outcome for a duplicate, when one was recorded. */
public Optional<String> replayOutcome(GrpcClientStreamMessage<?> message) {
return Optional.ofNullable(replayableOutcomes.get(message.dedupKey()));
}
/** The checkpoint for a session. */
public Optional<GrpcClientStreamCheckpoint> checkpointOf(GrpcClientStreamSessionId sessionId) {
return Optional.ofNullable(checkpoints.get(sessionId.value()));
}
/** Whether a reconnecting client may continue. */
public GrpcClientStreamResumeDecision decideResume(
GrpcClientStreamSessionId presented, String presentedCaller, String sessionOwner) {
if (presented == null) {
throw new IllegalArgumentException("a resume needs a presented session");
}
if (presentedCaller == null || !presentedCaller.equals(sessionOwner)) {
return GrpcClientStreamResumeDecision.reject(
"the presented session belongs to a different caller");
}
GrpcClientStreamCheckpoint checkpoint = checkpoints.get(presented.value());
if (checkpoint == null) {
return GrpcClientStreamResumeDecision.newSession(
"the server holds no checkpoint for this session; resuming would leave its prefix either "
+ "lost or applied twice, with nothing to tell which");
}
return GrpcClientStreamResumeDecision.resume(
checkpoint.lastAppliedSequence(), "continuing from the last applied message");
}
/** Forgets a finished session. */
public void endSession(GrpcClientStreamSessionId sessionId) {
checkpoints.remove(sessionId.value());
replayableOutcomes.keySet().removeIf(key -> key.startsWith(sessionId.value() + "|"));
}
private GrpcClientStreamCheckpoint requireCheckpoint(GrpcClientStreamSessionId sessionId) {
GrpcClientStreamCheckpoint checkpoint = checkpoints.get(sessionId.value());
if (checkpoint == null) {
throw new IllegalStateException(
"no session is open for '" + sessionId.value() + "'; call beginSession first");
}
return checkpoint;
}
}
@@ -0,0 +1,56 @@
package dev.caskeleton.grpc.advanced.streaming;
import java.time.Instant;
/**
* How far a client stream's messages have actually been applied.
*
* <p>Applied, not received. The distinction is the whole contract: the transport acknowledging a
* message means it reached the server's buffer, and a checkpoint means the application committed
* its effect. A resume that continues from a transport acknowledgement skips everything that was
* received and not yet applied when the connection died.
*/
public record GrpcClientStreamCheckpoint(
GrpcClientStreamSessionId sessionId, long lastAppliedSequence, Instant checkpointedAt) {
/** Requires a session, a non-negative position and a moment. */
public GrpcClientStreamCheckpoint {
if (sessionId == null) {
throw new IllegalArgumentException("a checkpoint belongs to a session");
}
if (lastAppliedSequence < 0) {
throw new IllegalArgumentException("an applied sequence is at or after zero");
}
if (checkpointedAt == null) {
throw new IllegalArgumentException("a checkpoint records when it was taken");
}
}
/** A session that has applied nothing yet. */
public static GrpcClientStreamCheckpoint empty(GrpcClientStreamSessionId sessionId, Instant at) {
return new GrpcClientStreamCheckpoint(sessionId, 0L, at);
}
/**
* Advances the checkpoint.
*
* @throws IllegalArgumentException when it would go backwards, which means two writers are
* checkpointing the same session
*/
public GrpcClientStreamCheckpoint advancedTo(long appliedSequence, Instant at) {
if (appliedSequence < lastAppliedSequence) {
throw new IllegalArgumentException(
"a checkpoint cannot move backwards from "
+ lastAppliedSequence
+ " to "
+ appliedSequence
+ "; two writers are checkpointing one session");
}
return new GrpcClientStreamCheckpoint(sessionId, appliedSequence, at);
}
/** Whether a message at {@code sequence} has already been applied. */
public boolean alreadyApplied(long sequence) {
return sequence <= lastAppliedSequence;
}
}
@@ -0,0 +1,32 @@
package dev.caskeleton.grpc.advanced.streaming;
/**
* One message a client sends, carrying the session and sequence that make it identifiable.
*
* <p>The sequence is the client's, not the transport's. gRPC guarantees ordering within a stream
* and says nothing about a stream that was re-established; a client that reconnects and resends
* needs its own numbering for the server to tell a resend from a new message.
*
* @param <T> the payload type
*/
public record GrpcClientStreamMessage<T>(
GrpcClientStreamSessionId sessionId, long sequence, T payload) {
/** Requires a session, a one-based sequence and a payload. */
public GrpcClientStreamMessage {
if (sessionId == null) {
throw new IllegalArgumentException("a client stream message belongs to a session");
}
if (sequence < 1) {
throw new IllegalArgumentException("client stream sequences are 1-based; got " + sequence);
}
if (payload == null) {
throw new IllegalArgumentException("a client stream message carries a payload");
}
}
/** The dedup key for this message. */
public String dedupKey() {
return sessionId.dedupKey(sequence);
}
}
@@ -0,0 +1,50 @@
package dev.caskeleton.grpc.advanced.streaming;
import java.time.Duration;
/**
* The bounds a client stream runs under.
*
* <p>A client stream is an inbound firehose with a single response at the end, so all four bounds
* are about the client rather than the server: how long it may hold the stream, how long it may go
* quiet, how fast it may send, and how much it may have unacknowledged. Without them, one client
* can occupy a server thread indefinitely while sending nothing.
*
* <p>Whole-stream transparent retry is not a setting. It is refused, because replaying a stream the
* server partially applied applies its prefix twice.
*/
public record GrpcClientStreamPolicy(
Duration maxDuration, Duration idleTimeout, int maxMessagesPerSecond, int maxInFlightMessages) {
/** Refuses an unbounded client stream. */
public GrpcClientStreamPolicy {
if (maxDuration == null || maxDuration.isZero() || maxDuration.isNegative()) {
throw new IllegalArgumentException("a client stream needs a maximum duration");
}
if (idleTimeout == null || idleTimeout.isZero() || idleTimeout.isNegative()) {
throw new IllegalArgumentException("a client stream needs an idle timeout");
}
if (idleTimeout.compareTo(maxDuration) > 0) {
throw new IllegalArgumentException(
"an idle timeout longer than the max duration never fires");
}
if (maxMessagesPerSecond < 1 || maxInFlightMessages < 1) {
throw new IllegalArgumentException("message rate and in-flight bounds must be positive");
}
}
/** A default for an upload-shaped client stream. */
public static GrpcClientStreamPolicy standard() {
return new GrpcClientStreamPolicy(Duration.ofMinutes(10), Duration.ofSeconds(30), 500, 64);
}
/**
* Whether a whole client stream may be transparently retried.
*
* <p>Always false. A stream whose prefix the server already applied cannot be replayed without
* applying that prefix again, and the transport has no way to know how much was applied.
*/
public boolean wholeStreamRetryAllowed() {
return false;
}
}
@@ -0,0 +1,58 @@
package dev.caskeleton.grpc.advanced.streaming;
import java.util.Optional;
/**
* Whether a reconnecting client may continue its session.
*
* <p>{@link Verdict#NEW_SESSION_REQUIRED} is what a server says when it no longer holds the
* checkpoint. Letting the client resume anyway would mean accepting messages numbered from where it
* thinks it stopped, against a server that has no record of the prefix — so the prefix is either
* lost or applied twice, and nothing detects which.
*/
public record GrpcClientStreamResumeDecision(
Verdict verdict, Optional<Long> resumeFromSequence, String reason) {
/** What the server decided. */
public enum Verdict {
/** Continue from the checkpoint. */
RESUME,
/** The session is gone; start a new one and resend everything. */
NEW_SESSION_REQUIRED,
/** The presented session does not belong to this caller. */
REJECTED
}
/** Requires a sequence only on RESUME. */
public GrpcClientStreamResumeDecision {
if (verdict == null || resumeFromSequence == null) {
throw new IllegalArgumentException(
"a resume decision has a verdict and the sequence Optional");
}
if (reason == null || reason.isBlank()) {
throw new IllegalArgumentException("a resume decision explains itself");
}
if (verdict == Verdict.RESUME && resumeFromSequence.isEmpty()) {
throw new IllegalArgumentException("a RESUME decision says where to continue from");
}
if (verdict != Verdict.RESUME && resumeFromSequence.isPresent()) {
throw new IllegalArgumentException("only a RESUME decision carries a sequence");
}
}
/** Continue from {@code sequence}. */
public static GrpcClientStreamResumeDecision resume(long sequence, String reason) {
return new GrpcClientStreamResumeDecision(Verdict.RESUME, Optional.of(sequence), reason);
}
/** Start over. */
public static GrpcClientStreamResumeDecision newSession(String reason) {
return new GrpcClientStreamResumeDecision(
Verdict.NEW_SESSION_REQUIRED, Optional.empty(), reason);
}
/** Refuse the presented session. */
public static GrpcClientStreamResumeDecision reject(String reason) {
return new GrpcClientStreamResumeDecision(Verdict.REJECTED, Optional.empty(), reason);
}
}
@@ -0,0 +1,46 @@
package dev.caskeleton.grpc.advanced.streaming;
import java.util.UUID;
/**
* A client stream's identity, plus the generation a reconnect advances.
*
* <p>The generation is what makes dedup possible across a reconnect. Message 7 of generation 1 and
* message 7 of generation 2 are different messages; a dedup key that ignores the generation drops
* the second, and the caller's seventh message is silently never applied.
*/
public record GrpcClientStreamSessionId(String value, long generation) {
/** Requires a bounded id and a positive generation. */
public GrpcClientStreamSessionId {
if (value == null || value.isBlank() || value.length() > 64) {
throw new IllegalArgumentException("a session id is a bounded non-blank identifier");
}
if (generation < 1) {
throw new IllegalArgumentException("session generations are 1-based; got " + generation);
}
}
/** A fresh session. */
public static GrpcClientStreamSessionId newSession() {
return new GrpcClientStreamSessionId(UUID.randomUUID().toString(), 1L);
}
/** The same session, resumed. */
public GrpcClientStreamSessionId resumed() {
return new GrpcClientStreamSessionId(value, generation + 1);
}
/** Whether {@code other} is the same logical session in any generation. */
public boolean sameSessionAs(GrpcClientStreamSessionId other) {
return other != null && value.equals(other.value());
}
/** The dedup key for a message at {@code sequence} in this generation. */
public String dedupKey(long sequence) {
if (sequence < 1) {
throw new IllegalArgumentException("client stream sequences are 1-based");
}
return value + "|" + generation + "|" + sequence;
}
}
@@ -0,0 +1,36 @@
package dev.caskeleton.grpc.advanced.streaming;
/**
* Where a client stream is in its life.
*
* <p>{@link #HALF_CLOSED} is separate from {@link #COMPLETED} because the server is still working
* between them: the client has said it will send nothing more, and the single response has not
* arrived. A state machine that merges them cannot express "we are waiting for the result of what
* we sent", which is the only interesting moment in a client stream.
*/
public enum GrpcClientStreamState {
/** Accepting messages from the client. */
OPEN(true),
/** The client has finished sending; the server is producing its response. */
HALF_CLOSED(false),
/** The server responded. */
COMPLETED(false),
/** The stream ended without a response. */
CANCELLED(false);
private final boolean acceptsMessages;
GrpcClientStreamState(boolean acceptsMessages) {
this.acceptsMessages = acceptsMessages;
}
/** Whether another client message may be accepted. */
public boolean acceptsMessages() {
return acceptsMessages;
}
/** Whether the stream has finished, one way or another. */
public boolean terminal() {
return this == COMPLETED || this == CANCELLED;
}
}
@@ -0,0 +1,105 @@
package dev.caskeleton.grpc.advanced.streaming;
import java.time.Duration;
import java.time.Instant;
/**
* Tracks demand in one direction and refuses to let it grow past its bound.
*
* <p>Never returns the underlying observer. Handing an application the raw {@code
* ServerCallStreamObserver} gives it {@code request(n)} with no ceiling and {@code onNext} with no
* serialization, which is both bounds gone at once; this controller is what the application talks
* to instead.
*
* <p>The watchdog compares two moments rather than sleeping: when demand was last requested, and
* when a message last moved. Both stalling for the timeout is the deadlock.
*/
public final class GrpcDemandController {
private final GrpcManualFlowControlPolicy policy;
private int outstandingDemand;
private Instant lastDemandRequestedAt;
private Instant lastMessageAt;
/** Starts a controller at {@code startedAt} with no outstanding demand. */
public GrpcDemandController(GrpcManualFlowControlPolicy policy, Instant startedAt) {
if (policy == null || startedAt == null) {
throw new IllegalArgumentException("a demand controller needs a policy and a start moment");
}
this.policy = policy;
this.lastDemandRequestedAt = startedAt;
this.lastMessageAt = startedAt;
}
/**
* Whether more may be requested at {@code now}.
*
* @param peerWaiting whether the other direction is itself blocked waiting for this one
*/
public synchronized GrpcDemandDecision decide(Instant now, boolean peerWaiting) {
if (now == null) {
throw new IllegalArgumentException("a demand decision needs a moment");
}
if (peerWaiting && stalledFor(now, policy.deadlockWatchdogTimeout())) {
return new GrpcDemandDecision(
GrpcDemandDecision.Action.DEADLOCK_SUSPECTED,
outstandingDemand,
"neither direction has moved for "
+ policy.deadlockWatchdogTimeout()
+ " while both are waiting; the stream is open and will never progress");
}
if (outstandingDemand >= policy.maxOutstandingDemand()) {
return new GrpcDemandDecision(
GrpcDemandDecision.Action.HOLD,
outstandingDemand,
"outstanding demand is at its ceiling of " + policy.maxOutstandingDemand());
}
return new GrpcDemandDecision(
GrpcDemandDecision.Action.REQUEST_MORE, outstandingDemand, "within the demand ceiling");
}
/**
* Records a request for {@code count} more messages.
*
* @throws IllegalArgumentException when it would exceed the ceiling
*/
public synchronized void request(int count, Instant now) {
if (count < 1) {
throw new IllegalArgumentException("a demand request is for at least one message");
}
if (outstandingDemand + count > policy.maxOutstandingDemand()) {
throw new IllegalArgumentException(
"requesting "
+ count
+ " more would take outstanding demand to "
+ (outstandingDemand + count)
+ ", above the ceiling of "
+ policy.maxOutstandingDemand());
}
outstandingDemand += count;
lastDemandRequestedAt = now;
}
/** Records that one message arrived, consuming a unit of demand. */
public synchronized void messageReceived(Instant now) {
if (outstandingDemand > 0) {
outstandingDemand--;
}
lastMessageAt = now;
}
/** How much demand is outstanding. */
public synchronized int outstandingDemand() {
return outstandingDemand;
}
/** The high-water mark a metric records. */
public synchronized int demandCeiling() {
return policy.maxOutstandingDemand();
}
private boolean stalledFor(Instant now, Duration timeout) {
return !now.isBefore(lastMessageAt.plus(timeout))
&& !now.isBefore(lastDemandRequestedAt.plus(timeout));
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.grpc.advanced.streaming;
/**
* Whether more inbound messages may be requested, or more outbound produced.
*
* <p>{@link Action#DEADLOCK_SUSPECTED} is a real answer rather than a diagnostic. Manual flow
* control makes it possible for both sides to be waiting for the other, and that state has no
* timeout of its own: the stream is healthy, the connection is open, and nothing will ever move
* again. Naming it is what lets a watchdog end the stream instead of leaking it.
*/
public record GrpcDemandDecision(Action action, int outstandingDemand, String reason) {
/** What the caller should do. */
public enum Action {
/** Request more inbound messages, or produce more outbound ones. */
REQUEST_MORE,
/** Hold: the outstanding demand is already at its bound. */
HOLD,
/** Neither side can move; end the stream. */
DEADLOCK_SUSPECTED
}
/** Requires a reason and a non-negative demand. */
public GrpcDemandDecision {
if (action == null) {
throw new IllegalArgumentException("a demand decision has an action");
}
if (outstandingDemand < 0) {
throw new IllegalArgumentException("outstanding demand must not be negative");
}
if (reason == null || reason.isBlank()) {
throw new IllegalArgumentException("a demand decision explains itself");
}
}
/** Whether the caller may ask for more. */
public boolean mayRequestMore() {
return action == Action.REQUEST_MORE;
}
}
@@ -0,0 +1,45 @@
package dev.caskeleton.grpc.advanced.streaming;
import java.time.Duration;
/**
* The bounds a manually flow-controlled stream runs under.
*
* <p>Manual flow control hands the application the {@code request(n)} call, which is exactly the
* knob automatic flow control exists to turn correctly. The two bounds here are what keep that from
* becoming unbounded buffering: a ceiling on outstanding demand, and a watchdog for the state where
* both sides are waiting.
*
* <p>Approval is a field because this capability is granted per method, not per service. A method
* that reads a large result set benefits; the one next to it does not, and enabling both because
* they share a service is how the second one acquires a bug nobody was looking for.
*/
public record GrpcManualFlowControlPolicy(
int maxOutstandingDemand, Duration deadlockWatchdogTimeout, boolean approvedForMethod) {
/** Refuses an unapproved or unbounded manual-flow-control policy. */
public GrpcManualFlowControlPolicy {
if (maxOutstandingDemand < 1) {
throw new IllegalArgumentException(
"manual flow control needs a demand ceiling; without one, request(n) is unbounded "
+ "buffering with extra steps");
}
if (deadlockWatchdogTimeout == null
|| deadlockWatchdogTimeout.isZero()
|| deadlockWatchdogTimeout.isNegative()) {
throw new IllegalArgumentException(
"manual flow control needs a watchdog; a stream where both sides wait for the other has "
+ "no timeout of its own");
}
if (!approvedForMethod) {
throw new IllegalArgumentException(
"manual flow control is granted per method; an unapproved policy would enable it for "
+ "every method on the service");
}
}
/** A policy for an approved method. */
public static GrpcManualFlowControlPolicy forApprovedMethod(int maxOutstandingDemand) {
return new GrpcManualFlowControlPolicy(maxOutstandingDemand, Duration.ofSeconds(30), true);
}
}
@@ -0,0 +1,60 @@
package dev.caskeleton.grpc.advanced.xds;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
/**
* What happens when the control plane goes away.
*
* <p>Last-known-good, with a bound. Serving forever from a stale snapshot means a decommissioned
* backend keeps receiving traffic indefinitely; failing immediately means a control-plane restart
* takes every client down with it. The bound is where the deployment decides which risk it prefers,
* and it has to be stated rather than inherited.
*/
public record GrpcXdsFailurePolicy(
Duration maxStaleness, boolean failFastOnMissingResource, Duration initialFetchTimeout) {
/** Refuses a policy without a staleness bound. */
public GrpcXdsFailurePolicy {
if (maxStaleness == null || maxStaleness.isZero() || maxStaleness.isNegative()) {
throw new IllegalArgumentException(
"last-known-good needs a staleness bound; without one a decommissioned backend keeps "
+ "receiving traffic indefinitely");
}
if (initialFetchTimeout == null
|| initialFetchTimeout.isZero()
|| initialFetchTimeout.isNegative()) {
throw new IllegalArgumentException(
"a client with no snapshot yet needs a bound on how long it waits before failing");
}
}
/** The default: fifteen minutes of last-known-good, fail fast on a resource that vanished. */
public static GrpcXdsFailurePolicy standard() {
return new GrpcXdsFailurePolicy(Duration.ofMinutes(15), true, Duration.ofSeconds(15));
}
/** What a client should do given the newest snapshot it holds. */
public Decision decide(Optional<GrpcXdsResourceSnapshot> snapshot, Instant now) {
if (snapshot == null || now == null) {
throw new IllegalArgumentException("a decision needs the snapshot Optional and a moment");
}
if (snapshot.isEmpty()) {
return Decision.NO_SNAPSHOT_YET;
}
return snapshot.get().ageAt(now).compareTo(maxStaleness) > 0
? Decision.STALE_BEYOND_BOUND
: Decision.SERVE_LAST_KNOWN_GOOD;
}
/** What the client does about a control-plane outage. */
public enum Decision {
/** Nothing has arrived yet; wait until the initial fetch timeout, then fail. */
NO_SNAPSHOT_YET,
/** Keep routing on the snapshot in hand. */
SERVE_LAST_KNOWN_GOOD,
/** The snapshot is older than the bound; stop trusting it. */
STALE_BEYOND_BOUND
}
}
@@ -0,0 +1,52 @@
package dev.caskeleton.grpc.advanced.xds;
import dev.caskeleton.grpc.resilience.GrpcRetryOwner;
import java.net.URI;
/**
* A proxyless xDS deployment's configuration.
*
* <p>xDS moves routing, load balancing, retries and often mTLS out of the application and into a
* control plane. The consequence this profile encodes is that the application must stop configuring
* them: retry policy defined in both places is defined twice, and which one wins depends on
* resolution order rather than on anyone's decision.
*/
public record GrpcXdsProfile(
URI target,
String bootstrapReference,
String resourceNamespace,
GrpcRetryOwner retryOwner,
boolean controlPlaneMutualTls) {
/** The only scheme an xDS target may use. */
public static final String XDS_SCHEME = "xds";
/** Refuses a profile that would leave retries or routing owned in two places. */
public GrpcXdsProfile {
if (target == null || !XDS_SCHEME.equals(target.getScheme())) {
throw new IllegalArgumentException(
"an xDS profile needs an 'xds:///' target; got '" + target + "'");
}
if (bootstrapReference == null || bootstrapReference.isBlank()) {
throw new IllegalArgumentException(
"xDS needs a bootstrap reference; without one the client has no control plane to ask");
}
if (resourceNamespace == null || resourceNamespace.isBlank()) {
throw new IllegalArgumentException(
"an xDS profile names its resource namespace; a client that subscribes to everything "
+ "receives another team's routing");
}
if (retryOwner != GrpcRetryOwner.SERVICE_MESH) {
throw new IllegalArgumentException(
"xDS routing means the control plane owns retries; a retry owner of "
+ retryOwner
+ " would define retry policy in two places, and which wins depends on resolution "
+ "order rather than on a decision");
}
if (!controlPlaneMutualTls) {
throw new IllegalArgumentException(
"the control-plane connection carries routing and often certificates; it is authenticated "
+ "in both directions or it is a channel that can be impersonated");
}
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.grpc.advanced.xds;
import java.time.Instant;
import java.util.List;
/**
* What the control plane last said, and when.
*
* <p>The timestamp is what makes last-known-good usable. A snapshot with no age cannot answer
* whether the control plane has been silent for a minute or a day, and those are a transient blip
* and a serious incident.
*/
public record GrpcXdsResourceSnapshot(
String versionInfo, List<String> resourceNames, Instant receivedAt) {
/** Requires a version, at least one resource and a receipt time. */
public GrpcXdsResourceSnapshot {
if (versionInfo == null || versionInfo.isBlank()) {
throw new IllegalArgumentException("an xDS snapshot carries the control plane's version");
}
if (resourceNames == null || resourceNames.isEmpty()) {
throw new IllegalArgumentException(
"an empty resource set is not a snapshot; a control plane that returns nothing has not "
+ "told the client its routing was removed");
}
if (receivedAt == null) {
throw new IllegalArgumentException(
"a snapshot records when it arrived; without it, last-known-good cannot say how old it is");
}
resourceNames = List.copyOf(resourceNames);
}
/** How old this snapshot is at {@code now}. */
public java.time.Duration ageAt(Instant now) {
if (now == null) {
throw new IllegalArgumentException("an age needs a moment");
}
return java.time.Duration.between(receivedAt, now);
}
}
@@ -0,0 +1,113 @@
package dev.caskeleton.grpc.advanced.bootstrap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcAdvancedModuleGuardTest {
@Test
@DisplayName("every advanced capability is off unless a deployment names it")
void everythingIsOffByDefault() {
GrpcAdvancedFeatureFlags flags = GrpcAdvancedFeatureFlags.forDevelopment();
assertThat(flags.active()).isEmpty();
for (GrpcAdvancedCapability capability : GrpcAdvancedCapability.values()) {
assertThat(GrpcAdvancedModuleGuard.available(flags, capability)).isFalse();
}
}
@Test
@DisplayName("each capability has its own flag, not a shared one")
void eachCapabilityHasItsOwnFlag() {
assertThat(GrpcAdvancedCapability.XDS.propertyKey()).isEqualTo("app.grpc.advanced.xds.enabled");
assertThat(GrpcAdvancedCapability.GRPC_WEB.propertyKey())
.isNotEqualTo(GrpcAdvancedCapability.XDS.propertyKey());
GrpcAdvancedFeatureFlags flags =
GrpcAdvancedFeatureFlags.forDevelopment().enable(GrpcAdvancedCapability.GRPC_WEB);
assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.GRPC_WEB)).isTrue();
assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.XDS)).isFalse();
}
@Test
@DisplayName("an unflagged capability is refused, and the message names the key to set")
void anUnflaggedCapabilityNamesItsKey() {
assertThatThrownBy(
() ->
GrpcAdvancedModuleGuard.require(
GrpcAdvancedFeatureFlags.forDevelopment(), GrpcAdvancedCapability.REACTOR))
.isInstanceOf(GrpcAdvancedCapabilityDisabledException.class)
.hasMessageContaining("app.grpc.advanced.reactor.enabled=true");
}
@Test
@DisplayName("a WATCH capability cannot be enabled, however loudly it is flagged")
void aWatchCapabilityCannotStart() {
GrpcAdvancedFeatureFlags flags =
GrpcAdvancedFeatureFlags.forDevelopment().enable(GrpcAdvancedCapability.EDITION_2026);
assertThat(GrpcAdvancedCapability.EDITION_2026.defaultGrade())
.isEqualTo(GrpcCapabilityGrade.WATCH);
assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.EDITION_2026))
.isFalse();
assertThatThrownBy(
() -> GrpcAdvancedModuleGuard.require(flags, GrpcAdvancedCapability.EDITION_2026))
.isInstanceOf(GrpcAdvancedCapabilityDisabledException.class)
.hasMessageContaining("tracked rather than implemented");
}
@Test
@DisplayName("an experimental capability needs a second approval in production")
void experimentalCapabilitiesNeedAProductionApproval() {
GrpcAdvancedFeatureFlags unapproved =
GrpcAdvancedFeatureFlags.forProduction(Set.of()).enable(GrpcAdvancedCapability.XDS);
GrpcAdvancedFeatureFlags approved =
GrpcAdvancedFeatureFlags.forProduction(Set.of(GrpcAdvancedCapability.XDS))
.enable(GrpcAdvancedCapability.XDS);
assertThat(GrpcAdvancedModuleGuard.available(unapproved, GrpcAdvancedCapability.XDS)).isFalse();
assertThat(GrpcAdvancedModuleGuard.available(approved, GrpcAdvancedCapability.XDS)).isTrue();
assertThatThrownBy(
() -> GrpcAdvancedModuleGuard.require(unapproved, GrpcAdvancedCapability.XDS))
.isInstanceOf(GrpcAdvancedCapabilityDisabledException.class)
.hasMessageContaining("uncharacterised failure modes");
}
@Test
@DisplayName("an experimental capability runs outside production on its flag alone")
void experimentalCapabilitiesRunInDevelopment() {
GrpcAdvancedFeatureFlags flags =
GrpcAdvancedFeatureFlags.forDevelopment().enable(GrpcAdvancedCapability.HEDGING);
assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.HEDGING)).isTrue();
GrpcAdvancedModuleGuard.require(flags, GrpcAdvancedCapability.HEDGING);
}
@Test
@DisplayName("only flagged and permitted capabilities appear as active")
void activeReflectsBothFlagAndGrade() {
GrpcAdvancedFeatureFlags flags =
GrpcAdvancedFeatureFlags.forProduction(Set.of())
.enable(GrpcAdvancedCapability.GRPC_WEB)
.enable(GrpcAdvancedCapability.XDS)
.enable(GrpcAdvancedCapability.EDITION_2026);
assertThat(flags.active()).containsExactly(GrpcAdvancedCapability.GRPC_WEB);
}
@Test
@DisplayName("a deployment may raise a capability's grade on its own evidence")
void aDeploymentMayOverrideAGrade() {
GrpcAdvancedFeatureFlags flags =
GrpcAdvancedFeatureFlags.forProduction(Set.of())
.enable(GrpcAdvancedCapability.HEDGING)
.withGrade(GrpcAdvancedCapability.HEDGING, GrpcCapabilityGrade.ADVANCED_STABLE);
assertThat(GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.HEDGING)).isTrue();
}
}
@@ -0,0 +1,205 @@
package dev.caskeleton.grpc.advanced.diagnostics;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability;
import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedFeatureFlags;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcChannelDiagnosticsPolicyTest {
private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z");
@Test
@DisplayName("diagnostics need both an admin network and an admin role")
void diagnosticsNeedBothGates() {
GrpcChannelDiagnosticsPolicy policy = GrpcChannelDiagnosticsPolicy.standard();
assertThat(policy.mayRead("admin", Set.of("ROLE_PLATFORM_ADMIN"))).isTrue();
assertThat(policy.mayRead("public", Set.of("ROLE_PLATFORM_ADMIN"))).isFalse();
assertThat(policy.mayRead("admin", Set.of("ROLE_USER"))).isFalse();
assertThatThrownBy(() -> new GrpcChannelDiagnosticsPolicy(Set.of("admin"), Set.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("either gate alone is the whole surface");
}
@Test
@DisplayName("CSDS is registered only when xDS is actually enabled")
void csdsFollowsXds() {
GrpcAdvancedFeatureFlags diagnosticsOnly =
GrpcAdvancedFeatureFlags.forDevelopment()
.enable(GrpcAdvancedCapability.CHANNEL_DIAGNOSTICS);
GrpcAdvancedFeatureFlags withXds =
GrpcAdvancedFeatureFlags.forDevelopment()
.enable(GrpcAdvancedCapability.CHANNEL_DIAGNOSTICS)
.enable(GrpcAdvancedCapability.XDS);
assertThat(GrpcChannelDiagnosticsPolicy.registerChannelz(diagnosticsOnly)).isTrue();
assertThat(GrpcChannelDiagnosticsPolicy.registerCsds(diagnosticsOnly)).isFalse();
assertThat(GrpcChannelDiagnosticsPolicy.registerCsds(withXds)).isTrue();
assertThat(
GrpcChannelDiagnosticsPolicy.registerChannelz(
GrpcAdvancedFeatureFlags.forDevelopment()))
.isFalse();
}
@Test
@DisplayName("credential, certificate, metadata and payload fields are dropped outright")
void sensitiveFieldsAreDropped() {
Map<String, String> raw = new LinkedHashMap<>();
raw.put("connectivityState", "READY");
raw.put("authorization", "Bearer abc");
raw.put("peerCertificate", "-----BEGIN CERTIFICATE-----");
raw.put("lastCallMetadata", "x-tenant=acme");
raw.put("requestPayload", "{...}");
Map<String, String> redacted = GrpcDiagnosticsRedactor.redact(raw, Set.of());
assertThat(redacted).containsOnlyKeys("connectivityState");
assertThat(GrpcDiagnosticsRedactor.forbiddenField("privateKeyRef")).isTrue();
assertThat(GrpcDiagnosticsRedactor.forbiddenField("subchannelCount")).isFalse();
}
@Test
@DisplayName("addresses are masked so two subchannels stay distinguishable but unresolvable")
void addressesAreMaskedRatherThanDropped() {
assertThat(GrpcDiagnosticsRedactor.maskAddress("10.4.13.201:9090")).isEqualTo("10.4.x.x");
assertThat(GrpcDiagnosticsRedactor.maskAddress("10.9.13.201")).isEqualTo("10.9.x.x");
String ipv6 = GrpcDiagnosticsRedactor.maskAddress("[2001:db8::10]:9090");
String hostname = GrpcDiagnosticsRedactor.maskAddress("payments.internal.example:443");
assertThat(ipv6).startsWith("masked:").doesNotContain("2001", "db8");
assertThat(hostname).startsWith("masked:").doesNotContain("payments", "internal.example");
assertThat(ipv6).isNotEqualTo(hostname);
assertThat(GrpcDiagnosticsRedactor.maskAddress(null)).isEqualTo("unknown");
Map<String, String> redacted =
GrpcDiagnosticsRedactor.redact(
Map.of("remoteAddress", "10.4.13.201:9090"), Set.of("remoteAddress"));
assertThat(redacted).containsEntry("remoteAddress", "10.4.x.x");
}
@Test
@DisplayName("a snapshot carrying an unmasked address is refused")
void anUnmaskedAddressIsRefused() {
assertThatThrownBy(
() ->
new GrpcChannelDiagnosticsSnapshot(
"documents-read",
"READY",
3,
100L,
98L,
2L,
List.of("10.4.13.201:9090"),
Map.of(),
NOW))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("every tenant's connection");
}
@Test
@DisplayName("a snapshot carries counters and states, and is accepted when masked")
void aMaskedSnapshotIsAccepted() {
GrpcChannelDiagnosticsSnapshot snapshot =
new GrpcChannelDiagnosticsSnapshot(
"documents-read",
"READY",
3,
100L,
98L,
2L,
List.of("10.4.x.x", "10.5.x.x"),
Map.of("documents-cluster", "v7"),
NOW);
assertThat(snapshot.subchannelCount()).isEqualTo(3);
assertThat(snapshot.xdsResourceVersions()).containsEntry("documents-cluster", "v7");
assertThat(snapshot.capturedAt()).isEqualTo(NOW);
}
@Test
@DisplayName("a snapshot carrying a forbidden field name is refused")
void aForbiddenFieldNameIsRefused() {
assertThatThrownBy(
() ->
new GrpcChannelDiagnosticsSnapshot(
"documents-read",
"READY",
1,
1L,
1L,
0L,
List.of(),
Map.of("controlPlaneToken", "abc"),
NOW))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("may not appear in a diagnostics snapshot");
}
@Test
@DisplayName("the committed CSDS fixture is redacted into something publishable")
void theCommittedCsdsFixtureIsRedacted() {
String raw = resource("xds/control-plane-snapshot.json");
// The fixture deliberately contains the three shapes a snapshot must never carry, so the
// redactor is exercised against data shaped like the real thing.
assertThat(raw)
.contains("controlPlaneToken")
.contains("peerCertificate")
.contains("10.4.13.201:9090");
Map<String, String> fields = new LinkedHashMap<>();
fields.put("connectivityState", "READY");
fields.put("subchannelCount", "3");
fields.put("controlPlaneToken", "must-not-appear-in-a-snapshot");
fields.put("peerCertificate", "-----BEGIN CERTIFICATE-----");
fields.put("lastCallMetadata", "x-tenant=acme");
fields.put("remoteAddress", "10.4.13.201:9090");
Map<String, String> redacted = GrpcDiagnosticsRedactor.redact(fields, Set.of("remoteAddress"));
assertThat(redacted).containsOnlyKeys("connectivityState", "subchannelCount", "remoteAddress");
assertThat(redacted.get("remoteAddress")).isEqualTo("10.4.x.x");
assertThat(String.join("|", redacted.values())).doesNotContain("must-not-appear-in-a-snapshot");
}
@Test
@DisplayName("a snapshot built from the fixture's resource versions is accepted")
void aSnapshotFromTheFixtureIsAccepted() {
assertThat(resource("xds/control-plane-snapshot.json")).contains("documents-cluster");
GrpcChannelDiagnosticsSnapshot snapshot =
new GrpcChannelDiagnosticsSnapshot(
"documents-read",
"READY",
3,
100L,
98L,
2L,
List.of("10.4.x.x", "10.4.x.x", "10.5.x.x"),
Map.of("documents-cluster", "v7", "documents-route", "v7", "documents-listener", "v6"),
NOW);
assertThat(snapshot.xdsResourceVersions()).hasSize(3);
}
private static String resource(String path) {
try (java.io.InputStream stream =
GrpcChannelDiagnosticsPolicyTest.class.getClassLoader().getResourceAsStream(path)) {
if (stream == null) {
throw new IllegalStateException("missing test resource " + path);
}
return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
} catch (java.io.IOException e) {
throw new java.io.UncheckedIOException(e);
}
}
}
@@ -0,0 +1,52 @@
package dev.caskeleton.grpc.advanced.diagnostics;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Masking an address twice gives the same answer as masking it once.
*
* <p>Not a style preference. {@code GrpcChannelDiagnosticsSnapshot} decides whether an address is
* masked by masking it and comparing, because a masked address carries no marker to look for — so
* the only way that question has an answer is if masking is idempotent. It was not: {@code
* 10.4.x.x} has no four numeric octets, fell through to the hash branch, and came back as {@code
* masked:<digest>}, which made a snapshot assembled from correctly masked addresses fail its own
* admission check. The property is asserted here, next to the function that has to hold it.
*/
class GrpcDiagnosticsRedactorIdempotenceTest {
@Test
@DisplayName("masking a masked IPv4 address returns it unchanged")
void maskingAMaskedIpv4AddressIsANoOp() {
String masked = GrpcDiagnosticsRedactor.maskAddress("10.4.7.19:8443");
assertThat(masked).isEqualTo("10.4.x.x");
assertThat(GrpcDiagnosticsRedactor.maskAddress(masked)).isEqualTo(masked);
}
@Test
@DisplayName("masking a masked non-IPv4 address returns it unchanged")
void maskingAMaskedOpaqueAddressIsANoOp() {
String masked = GrpcDiagnosticsRedactor.maskAddress("unix:///var/run/grpc.sock");
assertThat(masked).startsWith("masked:");
assertThat(GrpcDiagnosticsRedactor.maskAddress(masked)).isEqualTo(masked);
}
@Test
@DisplayName("the placeholder for an absent address is its own mask")
void theUnknownPlaceholderIsStable() {
assertThat(GrpcDiagnosticsRedactor.maskAddress("")).isEqualTo("unknown");
assertThat(GrpcDiagnosticsRedactor.maskAddress("unknown")).isEqualTo("unknown");
}
@Test
@DisplayName("an address that only looks masked is still masked")
void anAddressThatMerelyResemblesTheMaskIsStillMasked() {
// `x.x` is the mask's own suffix, so a value ending in it must not be waved through unless the
// whole value is a mask — otherwise "10.4.7.19 x.x" would be accepted as already redacted.
assertThat(GrpcDiagnosticsRedactor.maskAddress("10.4.7.19 x.x")).isNotEqualTo("10.4.7.19 x.x");
}
}
@@ -0,0 +1,95 @@
package dev.caskeleton.grpc.advanced.edition;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcEdition2024PolicyTest {
private static GrpcEditionCompatibilityReport report(
boolean wire, boolean json, Map<String, Boolean> toolchains) {
return new GrpcEditionCompatibilityReport("2024", wire, json, toolchains);
}
@Test
@DisplayName("Edition 2024 is module-level opt-in, and nothing is opted in by default")
void editionIsOptInPerModule() {
GrpcEdition2024Policy policy = GrpcEdition2024Policy.notAdopted();
assertThat(policy.allowedIn("grpc-contract")).isFalse();
assertThat(
new GrpcEdition2024Policy(Set.of("grpc-advanced"), Set.of(), false)
.allowedIn("grpc-advanced"))
.isTrue();
}
@Test
@DisplayName("a public service may not move onto the edition without a promotion")
void publicServicesNeedAPromotion() {
GrpcEdition2024Policy withoutPromotion =
new GrpcEdition2024Policy(
Set.of("grpc-advanced"), Set.of("caskeleton.document.v1.DocumentService"), false);
GrpcEdition2024Policy withPromotion =
new GrpcEdition2024Policy(
Set.of("grpc-advanced"), Set.of("caskeleton.document.v1.DocumentService"), true);
assertThat(withoutPromotion.serviceMayMove("caskeleton.document.v1.DocumentService")).isFalse();
assertThat(withPromotion.serviceMayMove("caskeleton.document.v1.DocumentService")).isTrue();
assertThat(withoutPromotion.serviceMayMove("caskeleton.internal.v1.ScratchService")).isTrue();
}
@Test
@DisplayName("Java compiling alone is not cross-language evidence")
void javaAloneIsNotEvidence() {
GrpcEditionCompatibilityReport javaOnlyBroken =
report(true, true, Map.of("java", true, "go", false, "python", true));
assertThat(javaOnlyBroken.fullyCompatible()).isFalse();
assertThat(javaOnlyBroken.brokenToolchains()).containsExactly("go");
assertThatThrownBy(() -> report(true, true, Map.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Java alone is not cross-language");
}
@Test
@DisplayName("wire, JSON and source compatibility are compared separately")
void threeComparisonsAreSeparate() {
assertThat(report(false, true, Map.of("java", true)).incompatibilities())
.singleElement()
.satisfies(problem -> assertThat(problem).contains("stored messages"));
assertThat(report(true, false, Map.of("java", true)).incompatibilities())
.singleElement()
.satisfies(problem -> assertThat(problem).contains("browser clients"));
}
@Test
@DisplayName("the Edition 2024 comparison fixture ships beside its proto3 twin")
void theComparisonFixtureShips() {
String source = resource("proto/edition2024/compatibility.proto");
assertThat(source)
.startsWith("edition = \"2024\";")
.contains("features.field_presence = EXPLICIT")
.contains("DOCUMENT_STATE_UNSPECIFIED = 0");
}
private static String resource(String path) {
try (InputStream stream =
GrpcEdition2024PolicyTest.class.getClassLoader().getResourceAsStream(path)) {
if (stream == null) {
throw new IllegalStateException("missing resource " + path);
}
return new String(stream.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,58 @@
package dev.caskeleton.grpc.advanced.edition;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Instant;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcEdition2026WatchReportTest {
private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z");
@Test
@DisplayName("the watch tracks four gates separately, because they land at different times")
void theWatchTracksFourGates() {
GrpcEdition2026WatchReport partial =
new GrpcEdition2026WatchReport(
GrpcEdition2026Status.RELEASED,
GrpcEdition2026Status.DRAFT,
GrpcEdition2026Status.UNKNOWN,
GrpcEdition2026Status.UNSUPPORTED,
NOW);
assertThat(partial.outstanding())
.hasSize(4)
.anySatisfy(item -> assertThat(item).contains("protoc support is DRAFT"))
.anySatisfy(item -> assertThat(item).contains("Buf support is UNKNOWN"))
.anySatisfy(item -> assertThat(item).contains("Java runtime support is UNSUPPORTED"));
assertThat(partial.readyToEvaluate()).isFalse();
assertThat(GrpcEdition2026WatchReport.nothingKnown(NOW).outstanding()).hasSize(4);
}
@Test
@DisplayName("a watch report is dated, so it cannot be told from a stale note")
void aWatchReportIsDated() {
assertThatThrownBy(
() ->
new GrpcEdition2026WatchReport(
GrpcEdition2026Status.SUPPORTED,
GrpcEdition2026Status.SUPPORTED,
GrpcEdition2026Status.SUPPORTED,
GrpcEdition2026Status.SUPPORTED,
null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("stale note");
}
@Test
@DisplayName("only SUPPORTED counts as usable")
void onlySupportedIsUsable() {
assertThat(GrpcEdition2026Status.SUPPORTED.usable()).isTrue();
assertThat(GrpcEdition2026Status.RELEASED.usable()).isFalse();
assertThat(GrpcEdition2026Status.DRAFT.usable()).isFalse();
assertThat(GrpcEdition2026Status.UNKNOWN.usable()).isFalse();
assertThat(GrpcEdition2026Status.UNSUPPORTED.usable()).isFalse();
}
}
@@ -0,0 +1,146 @@
package dev.caskeleton.grpc.advanced.resilience;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile;
import dev.caskeleton.grpc.api.policy.GrpcMethodPolicy;
import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile;
import dev.caskeleton.grpc.api.policy.WaitForReadyPolicy;
import dev.caskeleton.grpc.core.GrpcMethodName;
import dev.caskeleton.grpc.core.RpcType;
import dev.caskeleton.grpc.resilience.GrpcRetryOwner;
import java.time.Duration;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcHedgingEligibilityTest {
private static final GrpcMethodName GET =
GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument");
private static final GrpcMethodName CREATE =
GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument");
private static final GrpcMethodName WATCH =
GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments");
private static final GrpcDeadlineProfile TWO_SECONDS =
GrpcDeadlineProfile.of(Duration.ofSeconds(2));
@Test
@DisplayName("only a read-only unary method may be hedged")
void onlyReadOnlyUnaryMayBeHedged() {
assertThat(
GrpcHedgingEligibility.eligible(
GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS), GrpcRetryOwner.GRPC_PLATFORM))
.isTrue();
assertThat(
GrpcHedgingEligibility.refusalReason(
GrpcMethodPolicy.nonIdempotentUnary(CREATE, TWO_SECONDS),
GrpcRetryOwner.GRPC_PLATFORM))
.hasValueSatisfying(
reason -> assertThat(reason).contains("duplicates a success in progress"));
}
@Test
@DisplayName("a keyed mutation is still refused; an idempotency key does not make hedging safe")
void aKeyedMutationIsStillRefused() {
GrpcMethodPolicy keyed =
new GrpcMethodPolicy(
CREATE,
RpcType.UNARY,
RpcIdempotencyProfile.IDEMPOTENCY_KEY_REQUIRED,
TWO_SECONDS,
WaitForReadyPolicy.DISABLED,
false,
1024,
1024);
assertThat(GrpcHedgingEligibility.eligible(keyed, GrpcRetryOwner.GRPC_PLATFORM)).isFalse();
}
@Test
@DisplayName("a streaming method may not be hedged")
void streamingMayNotBeHedged() {
GrpcMethodPolicy streaming =
new GrpcMethodPolicy(
WATCH,
RpcType.SERVER_STREAMING,
RpcIdempotencyProfile.READ_ONLY,
TWO_SECONDS,
WaitForReadyPolicy.DISABLED,
false,
1024,
1024);
assertThatThrownBy(
() -> GrpcHedgingEligibility.require(streaming, GrpcRetryOwner.GRPC_PLATFORM))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("two prefixes");
}
@Test
@DisplayName("a mesh-owned channel may not hedge in-process")
void aMeshOwnedChannelMayNotHedge() {
assertThat(
GrpcHedgingEligibility.eligible(
GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS), GrpcRetryOwner.SERVICE_MESH))
.isFalse();
assertThat(
GrpcHedgingEligibility.eligible(
GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS), GrpcRetryOwner.APPLICATION))
.isFalse();
}
@Test
@DisplayName("hedging is capped at two attempts and needs a meaningful delay")
void hedgingIsCappedAndDelayed() {
assertThat(
GrpcHedgingPolicy.hedgeOnce(Duration.ofMillis(50), Duration.ofSeconds(2)).maxAttempts())
.isEqualTo(2);
assertThatThrownBy(() -> new GrpcHedgingPolicy(3, Duration.ofMillis(50), Duration.ofSeconds(2)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("capped at 2");
assertThatThrownBy(() -> new GrpcHedgingPolicy(2, Duration.ZERO, Duration.ofSeconds(2)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("doubles load for every call");
assertThatThrownBy(() -> new GrpcHedgingPolicy(2, Duration.ofSeconds(3), Duration.ofSeconds(2)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("never starts");
}
@Test
@DisplayName("the hedging budget bounds duplicate load and refuses an absurd ratio")
void theHedgingBudgetBoundsDuplicateLoad() {
// ratio 0.5 costs two tokens per hedge, so a four-token budget affords two hedges and then
// needs two completions before it can afford another.
GrpcHedgingBudget budget = GrpcHedgingBudget.of(0.5d, 4L);
assertThat(budget.tryConsume()).isTrue();
assertThat(budget.tryConsume()).isTrue();
assertThat(budget.tryConsume()).isFalse();
assertThat(budget.availableTokens()).isZero();
budget.recordCompletion();
assertThat(budget.exhausted()).isTrue();
budget.recordCompletion();
assertThat(budget.exhausted()).isFalse();
assertThatThrownBy(() -> GrpcHedgingBudget.of(0.9d, 10L))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("load decision rather than a latency one");
}
@Test
@DisplayName("a hedged result records both the saving and the duplicate load")
void aHedgedResultRecordsBothSides() {
GrpcHedgingResult hedged = new GrpcHedgingResult(2, 2, 1, 1, Duration.ofMillis(40));
assertThat(hedged.hedged()).isTrue();
assertThat(hedged.duplicateBackendCalls()).isEqualTo(1);
assertThat(hedged.cancelledLoserAttempts()).isEqualTo(1);
assertThat(GrpcHedgingResult.firstAttemptWon(Duration.ofMillis(10)).hedged()).isFalse();
assertThatThrownBy(() -> new GrpcHedgingResult(2, 3, 0, 0, Duration.ZERO))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new GrpcHedgingResult(2, 1, 2, 0, Duration.ZERO))
.isInstanceOf(IllegalArgumentException.class);
}
}
@@ -0,0 +1,124 @@
package dev.caskeleton.grpc.advanced.resilience;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.grpc.advanced.discovery.GrpcEndpointCandidate;
import dev.caskeleton.grpc.advanced.discovery.GrpcLoadBalancerDecision;
import dev.caskeleton.grpc.advanced.discovery.GrpcLoadBalancerPicker;
import dev.caskeleton.grpc.advanced.discovery.GrpcLoadBalancerSafetyPolicy;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcLoadBalancerSafetyPolicyTest {
@Test
@DisplayName("a picker may only choose an endpoint the resolver supplied")
void aPickerMayNotInventAnEndpoint() {
GrpcLoadBalancerSafetyPolicy policy =
new GrpcLoadBalancerSafetyPolicy(candidates -> GrpcEndpointCandidate.ready("10.9.9.9"));
GrpcLoadBalancerDecision decision =
policy.pick(List.of(GrpcEndpointCandidate.ready("10.0.0.1")));
assertThat(decision.verdict())
.isEqualTo(GrpcLoadBalancerDecision.Verdict.DETERMINISTIC_FALLBACK);
assertThat(decision.reason()).contains("can send a request anywhere");
assertThat(decision.chosen())
.hasValueSatisfying(endpoint -> assertThat(endpoint.address()).isEqualTo("10.0.0.1"));
}
@Test
@DisplayName("a picker that throws degrades balancing, not availability")
void aThrowingPickerFallsBack() {
GrpcLoadBalancerSafetyPolicy policy =
new GrpcLoadBalancerSafetyPolicy(
candidates -> {
throw new IllegalStateException("picker bug");
});
GrpcLoadBalancerDecision decision =
policy.pick(List.of(GrpcEndpointCandidate.ready("10.0.0.1")));
assertThat(decision.verdict())
.isEqualTo(GrpcLoadBalancerDecision.Verdict.DETERMINISTIC_FALLBACK);
assertThat(decision.reason()).contains("IllegalStateException");
}
@Test
@DisplayName("a picker returning null falls back rather than failing the call")
void aNullPickFallsBack() {
GrpcLoadBalancerSafetyPolicy policy = new GrpcLoadBalancerSafetyPolicy(candidates -> null);
assertThat(policy.pick(List.of(GrpcEndpointCandidate.ready("10.0.0.1"))).verdict())
.isEqualTo(GrpcLoadBalancerDecision.Verdict.DETERMINISTIC_FALLBACK);
}
@Test
@DisplayName("no selectable endpoint is a different verdict from a picker failure")
void noEndpointDiffersFromAPickerFailure() {
GrpcLoadBalancerSafetyPolicy policy =
new GrpcLoadBalancerSafetyPolicy(GrpcLoadBalancerPicker.roundRobin());
assertThat(
policy
.pick(List.of(new GrpcEndpointCandidate("10.0.0.1", false, true, 100, false)))
.verdict())
.isEqualTo(GrpcLoadBalancerDecision.Verdict.NO_ENDPOINT_AVAILABLE);
assertThat(
policy
.pick(List.of(new GrpcEndpointCandidate("10.0.0.1", true, true, 100, true)))
.verdict())
.isEqualTo(GrpcLoadBalancerDecision.Verdict.NO_ENDPOINT_AVAILABLE);
assertThat(
policy
.pick(List.of(new GrpcEndpointCandidate("10.0.0.1", true, true, 0, false)))
.verdict())
.isEqualTo(GrpcLoadBalancerDecision.Verdict.NO_ENDPOINT_AVAILABLE);
}
@Test
@DisplayName("a healthy endpoint is picked and reported as the picker's own choice")
void aHealthyEndpointIsPicked() {
GrpcLoadBalancerSafetyPolicy policy =
new GrpcLoadBalancerSafetyPolicy(GrpcLoadBalancerPicker.roundRobin());
assertThat(
policy
.pick(
List.of(
GrpcEndpointCandidate.ready("10.0.0.1"),
GrpcEndpointCandidate.ready("10.0.0.2")))
.verdict())
.isEqualTo(GrpcLoadBalancerDecision.Verdict.PICKED);
}
@Test
@DisplayName("a picker sees endpoints only, never a request or a caller")
void aPickerSeesEndpointsOnly() {
assertThat(GrpcLoadBalancerPicker.class.getMethods())
.filteredOn(method -> "pick".equals(method.getName()))
.singleElement()
.satisfies(method -> assertThat(method.getParameterCount()).isEqualTo(1));
}
@Test
@DisplayName("a candidate carries only routing-relevant state, bounded")
void aCandidateCarriesOnlyRoutingState() {
assertThat(GrpcEndpointCandidate.ready("10.0.0.1").selectable()).isTrue();
assertThatThrownBy(() -> new GrpcEndpointCandidate("10.0.0.1", true, true, 5000, false))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("scale nobody can reason about");
assertThatThrownBy(() -> new GrpcEndpointCandidate(" ", true, true, 100, false))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("a load-aware or weighted picker requires evidence before it ships")
void loadAwarePickersRequireEvidence() {
assertThat(GrpcLoadBalancerSafetyPolicy.requiresLoadEvidence(true, false)).isTrue();
assertThat(GrpcLoadBalancerSafetyPolicy.requiresLoadEvidence(false, true)).isTrue();
assertThat(GrpcLoadBalancerSafetyPolicy.requiresLoadEvidence(false, false)).isFalse();
}
}
@@ -0,0 +1,159 @@
package dev.caskeleton.grpc.advanced.resilience;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.grpc.advanced.discovery.GrpcCustomResolver;
import dev.caskeleton.grpc.advanced.discovery.GrpcEndpointSnapshot;
import dev.caskeleton.grpc.advanced.discovery.GrpcResolverSafetyPolicy;
import dev.caskeleton.grpc.advanced.discovery.GrpcResolverUpdate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcResolverSafetyPolicyTest {
@Test
@DisplayName("an empty or duplicate endpoint set is refused")
void anEmptyOrDuplicateEndpointSetIsRefused() {
assertThatThrownBy(() -> new GrpcEndpointSnapshot(1L, "documents", List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("take the channel down with it");
assertThatThrownBy(
() -> new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1", "10.0.0.1")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("skew a round-robin picker");
assertThatThrownBy(() -> new GrpcEndpointSnapshot(0L, "documents", List.of("10.0.0.1")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("a stale revision is dropped rather than applied")
void aStaleRevisionIsDropped() {
List<GrpcResolverUpdate> delivered = new ArrayList<>();
try (GrpcCustomResolver resolver = new GrpcCustomResolver("documents", delivered::add)) {
assertThat(
resolver.offer(
GrpcResolverUpdate.endpointsOnly(
new GrpcEndpointSnapshot(2L, "documents", List.of("10.0.0.1")))))
.isEmpty();
assertThat(
resolver.offer(
GrpcResolverUpdate.endpointsOnly(
new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.9")))))
.anySatisfy(violation -> assertThat(violation).contains("older ones"));
assertThat(delivered).hasSize(1);
assertThat(resolver.currentSnapshot())
.hasValueSatisfying(snapshot -> assertThat(snapshot.revision()).isEqualTo(2L));
assertThat(resolver.authority()).isEqualTo("documents");
}
}
@Test
@DisplayName("a resolver accepts nothing after close")
void aClosedResolverAcceptsNothing() {
List<GrpcResolverUpdate> delivered = new ArrayList<>();
GrpcCustomResolver resolver = new GrpcCustomResolver("documents", delivered::add);
resolver.close();
assertThat(resolver.closed()).isTrue();
assertThat(
resolver.offer(
GrpcResolverUpdate.endpointsOnly(
new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")))))
.anySatisfy(violation -> assertThat(violation).contains("resolver is closed"));
assertThat(delivered).isEmpty();
}
@Test
@DisplayName("a resolver may not push credentials or business metadata")
void aResolverMayNotPushCredentials() {
GrpcResolverUpdate withCredential =
new GrpcResolverUpdate(
new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")),
Optional.of(Map.of("authorization", "Bearer abc")));
assertThat(GrpcResolverSafetyPolicy.violations(withCredential, null))
.anySatisfy(violation -> assertThat(violation).contains("never authentication material"));
assertThat(GrpcResolverSafetyPolicy.acceptedServiceConfig(withCredential, null)).isEmpty();
}
@Test
@DisplayName("a clean service config survives validation")
void aCleanServiceConfigSurvives() {
GrpcResolverUpdate clean =
new GrpcResolverUpdate(
new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")),
Optional.of(Map.of("loadBalancingConfig", List.of(Map.of("round_robin", Map.of())))));
assertThat(GrpcResolverSafetyPolicy.violations(clean, null)).isEmpty();
assertThat(GrpcResolverSafetyPolicy.acceptedServiceConfig(clean, null)).isPresent();
}
@Test
void aServiceConfigWithRetryThrottlingIsAccepted() {
// given
GrpcResolverUpdate throttled =
new GrpcResolverUpdate(
new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")),
Optional.of(Map.of("retryThrottling", Map.of("maxTokens", 10, "tokenRatio", 0.1))));
// when
List<String> violations = GrpcResolverSafetyPolicy.violations(throttled, null);
// then
assertThat(violations).isEmpty();
}
@Test
void aServiceConfigThatTurnsOnRetriesIsRefused() {
// given
GrpcResolverUpdate retrying =
new GrpcResolverUpdate(
new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")),
Optional.of(
Map.of(
"methodConfig",
List.of(
Map.of(
"name", List.of(Map.of("service", "documents.v1.Documents")),
"retryPolicy", Map.of("maxAttempts", 5))))));
// when
List<String> violations = GrpcResolverSafetyPolicy.violations(retrying, null);
// then
assertThat(violations).singleElement().asString().contains("retryPolicy or hedgingPolicy");
}
@Test
@DisplayName("an invalid authority is refused, because it decides which certificate is accepted")
void anInvalidAuthorityIsRefused() {
assertThat(
GrpcResolverSafetyPolicy.violations(
GrpcResolverUpdate.endpointsOnly(
new GrpcEndpointSnapshot(1L, "Documents Service", List.of("10.0.0.1"))),
null))
.anySatisfy(violation -> assertThat(violation).contains("which certificate"));
}
@Test
void aPresentServiceConfigMayNotBeEmpty() {
// when
Throwable failure =
catchThrowable(
() ->
new GrpcResolverUpdate(
new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")),
Optional.of(Map.of())));
// then
assertThat(failure)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("absent and empty are different states");
}
}
@@ -0,0 +1,94 @@
package dev.caskeleton.grpc.advanced.resilience;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.grpc.advanced.xds.GrpcXdsFailurePolicy;
import dev.caskeleton.grpc.advanced.xds.GrpcXdsProfile;
import dev.caskeleton.grpc.advanced.xds.GrpcXdsResourceSnapshot;
import dev.caskeleton.grpc.resilience.GrpcRetryOwner;
import java.net.URI;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcXdsProfileTest {
private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z");
private static GrpcXdsProfile profile(String namespace) {
return new GrpcXdsProfile(
URI.create("xds:///documents"),
"classpath:/xds/bootstrap.json",
namespace,
GrpcRetryOwner.SERVICE_MESH,
true);
}
@Test
@DisplayName("an xDS profile requires an xds target, a namespace, mesh retries and mTLS")
void anXdsProfileRequiresItsFourConditions() {
assertThat(profile("caskeleton/documents").target().getScheme()).isEqualTo("xds");
assertThatThrownBy(
() ->
new GrpcXdsProfile(
URI.create("dns:///documents"),
"file:/etc/grpc/bootstrap.json",
"ns",
GrpcRetryOwner.SERVICE_MESH,
true))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(
() ->
new GrpcXdsProfile(
URI.create("xds:///documents"), " ", "ns", GrpcRetryOwner.SERVICE_MESH, true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("no control plane to ask");
assertThatThrownBy(
() ->
new GrpcXdsProfile(
URI.create("xds:///documents"),
"file:/etc/grpc/bootstrap.json",
"ns",
GrpcRetryOwner.APPLICATION,
true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("two places");
assertThatThrownBy(
() ->
new GrpcXdsProfile(
URI.create("xds:///documents"),
"file:/etc/grpc/bootstrap.json",
"ns",
GrpcRetryOwner.SERVICE_MESH,
false))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("impersonated");
}
@Test
@DisplayName("last-known-good is bounded, and an empty resource set is not a snapshot")
void lastKnownGoodIsBounded() {
GrpcXdsFailurePolicy policy = GrpcXdsFailurePolicy.standard();
GrpcXdsResourceSnapshot snapshot =
new GrpcXdsResourceSnapshot("v7", List.of("documents-cluster"), NOW);
assertThat(policy.decide(Optional.of(snapshot), NOW.plusSeconds(60)))
.isEqualTo(GrpcXdsFailurePolicy.Decision.SERVE_LAST_KNOWN_GOOD);
assertThat(policy.decide(Optional.of(snapshot), NOW.plusSeconds(1000)))
.isEqualTo(GrpcXdsFailurePolicy.Decision.STALE_BEYOND_BOUND);
assertThat(policy.decide(Optional.empty(), NOW))
.isEqualTo(GrpcXdsFailurePolicy.Decision.NO_SNAPSHOT_YET);
assertThat(snapshot.ageAt(NOW.plusSeconds(60))).isEqualTo(java.time.Duration.ofSeconds(60));
assertThatThrownBy(() -> new GrpcXdsResourceSnapshot("v7", List.of(), NOW))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(
() ->
new GrpcXdsFailurePolicy(
java.time.Duration.ZERO, true, java.time.Duration.ofSeconds(1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("receiving traffic indefinitely");
}
}
@@ -0,0 +1,108 @@
package dev.caskeleton.grpc.advanced.streaming;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.grpc.streaming.GrpcFlowControlPolicy;
import dev.caskeleton.grpc.streaming.GrpcSlowConsumerPolicy;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcBidiSequenceTrackerTest {
@Test
@DisplayName("the two directions have independent sequences")
void directionsAreIndependent() {
GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker();
assertThat(tracker.nextClientSequence()).isEqualTo(1L);
assertThat(tracker.nextClientSequence()).isEqualTo(2L);
assertThat(tracker.nextServerSequence()).isEqualTo(1L);
assertThat(tracker.clientToServer().lastSequence()).isEqualTo(2L);
assertThat(tracker.serverToClient().lastSequence()).isEqualTo(1L);
}
@Test
@DisplayName("half-closing one direction leaves the other open")
void halfClosingOneDirectionLeavesTheOtherOpen() {
GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker();
tracker.halfCloseClient();
assertThat(tracker.clientToServer().ended()).isTrue();
assertThat(tracker.serverToClient().ended()).isFalse();
assertThat(tracker.bothEnded()).isFalse();
assertThat(tracker.nextServerSequence()).isEqualTo(1L);
tracker.halfCloseServer();
assertThat(tracker.bothEnded()).isTrue();
}
@Test
@DisplayName("cancelling one direction leaves the other alone")
void cancellingOneDirectionLeavesTheOtherAlone() {
GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker();
tracker.cancelServer();
assertThat(tracker.serverToClient().cancelled()).isTrue();
assertThat(tracker.clientToServer().ended()).isFalse();
assertThat(tracker.nextClientSequence()).isEqualTo(1L);
}
@Test
@DisplayName("a message after half-close is a protocol error, not a late arrival")
void aMessageAfterHalfCloseIsAnError() {
GrpcBidiSequenceTracker tracker = new GrpcBidiSequenceTracker();
tracker.halfCloseClient();
assertThatThrownBy(tracker::nextClientSequence)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("protocol error");
}
@Test
@DisplayName("half-close and cancel are different endings")
void halfCloseAndCancelAreDifferent() {
assertThatThrownBy(() -> new GrpcBidiDirectionState(1L, true, true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("different endings");
assertThat(GrpcBidiDirectionState.open().cancel().ended()).isTrue();
assertThat(GrpcBidiDirectionState.open().halfClose().ended()).isTrue();
assertThatThrownBy(() -> GrpcBidiDirectionState.open().cancel().halfClose())
.isInstanceOf(IllegalStateException.class);
}
@Test
@DisplayName("a bidi resume carries both applied positions and requires a matching generation")
void aBidiResumeCarriesBothPositions() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
GrpcBidiSession bidi =
new GrpcBidiSession(
session, GrpcFlowControlPolicy.stable(), GrpcFlowControlPolicy.stable());
bidi.sequences().nextClientSequence();
bidi.sequences().nextServerSequence();
bidi.sequences().nextServerSequence();
GrpcBidiResumeState state = bidi.resumeState();
assertThat(state.clientAppliedSequence()).isEqualTo(1L);
assertThat(state.serverAppliedSequence()).isEqualTo(2L);
assertThat(bidi.resumeFrom(session)).isPresent();
assertThat(bidi.resumeFrom(session.resumed())).isEmpty();
assertThat(state.resumed().sessionId().generation()).isEqualTo(2L);
}
@Test
@DisplayName("each direction carries its own flow-control policy")
void eachDirectionHasItsOwnFlowControl() {
GrpcFlowControlPolicy inbound =
new GrpcFlowControlPolicy(8, 1024L, 4, GrpcSlowConsumerPolicy.TERMINATE);
GrpcBidiSession bidi =
new GrpcBidiSession(
GrpcClientStreamSessionId.newSession(), inbound, GrpcFlowControlPolicy.stable());
assertThat(bidi.inboundFlowControl().maxQueuedMessages()).isEqualTo(8);
assertThat(bidi.outboundFlowControl().maxQueuedMessages()).isEqualTo(256);
assertThat(bidi.complete()).isFalse();
}
}
@@ -0,0 +1,130 @@
package dev.caskeleton.grpc.advanced.streaming;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Instant;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcClientMessageDeduplicatorTest {
private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z");
private final GrpcClientMessageDeduplicator deduplicator = new GrpcClientMessageDeduplicator();
private static GrpcClientStreamMessage<String> message(
GrpcClientStreamSessionId session, long sequence) {
return new GrpcClientStreamMessage<>(session, sequence, "payload-" + sequence);
}
@Test
@DisplayName("a message is applied once, and a duplicate replays instead")
void aDuplicateReplaysRatherThanReapplying() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
deduplicator.beginSession(session, NOW);
GrpcClientStreamMessage<String> first = message(session, 1L);
assertThat(deduplicator.dispositionOf(first))
.isEqualTo(GrpcClientMessageDeduplicator.Disposition.APPLY);
deduplicator.recordApplied(first, "outcome://applied/1", NOW);
assertThat(deduplicator.dispositionOf(first))
.isEqualTo(GrpcClientMessageDeduplicator.Disposition.REPLAY);
assertThat(deduplicator.replayOutcome(first)).contains("outcome://applied/1");
}
@Test
@DisplayName("a message ahead of the checkpoint is a gap, not an application")
void aMessageAheadOfTheCheckpointIsAGap() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
deduplicator.beginSession(session, NOW);
assertThat(deduplicator.dispositionOf(message(session, 5L)))
.isEqualTo(GrpcClientMessageDeduplicator.Disposition.GAP);
}
@Test
@DisplayName("a message for a session the server never opened is an error")
void anUnknownSessionIsAnError() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
assertThatThrownBy(() -> deduplicator.dispositionOf(message(session, 1L)))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("beginSession");
}
@Test
@DisplayName("a checkpoint records what was applied, not what was received")
void aCheckpointRecordsWhatWasApplied() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
GrpcClientStreamCheckpoint checkpoint = GrpcClientStreamCheckpoint.empty(session, NOW);
assertThat(checkpoint.alreadyApplied(1L)).isFalse();
assertThat(checkpoint.advancedTo(3L, NOW).alreadyApplied(3L)).isTrue();
assertThatThrownBy(() -> checkpoint.advancedTo(3L, NOW).advancedTo(1L, NOW))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("two writers");
}
@Test
@DisplayName("a session the server no longer holds requires a new session, not a resume")
void aForgottenSessionRequiresANewOne() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
GrpcClientStreamResumeDecision decision =
deduplicator.decideResume(session, "tenant-1", "tenant-1");
assertThat(decision.verdict())
.isEqualTo(GrpcClientStreamResumeDecision.Verdict.NEW_SESSION_REQUIRED);
assertThat(decision.reason()).contains("nothing to tell which");
}
@Test
@DisplayName("a session presented by a different caller is refused")
void aSessionFromAnotherCallerIsRefused() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
deduplicator.beginSession(session, NOW);
assertThat(deduplicator.decideResume(session, "tenant-2", "tenant-1").verdict())
.isEqualTo(GrpcClientStreamResumeDecision.Verdict.REJECTED);
}
@Test
@DisplayName("a tracked session resumes from its last applied message")
void aTrackedSessionResumes() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
deduplicator.beginSession(session, NOW);
deduplicator.recordApplied(message(session, 1L), null, NOW);
deduplicator.recordApplied(message(session, 2L), null, NOW);
GrpcClientStreamResumeDecision decision =
deduplicator.decideResume(session, "tenant-1", "tenant-1");
assertThat(decision.verdict()).isEqualTo(GrpcClientStreamResumeDecision.Verdict.RESUME);
assertThat(decision.resumeFromSequence()).contains(2L);
assertThat(deduplicator.checkpointOf(session))
.hasValueSatisfying(c -> assertThat(c.lastAppliedSequence()).isEqualTo(2L));
}
@Test
@DisplayName("a finished session is forgotten along with its replayable outcomes")
void endingASessionForgetsIt() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
deduplicator.beginSession(session, NOW);
deduplicator.recordApplied(message(session, 1L), "outcome://applied/1", NOW);
deduplicator.endSession(session);
assertThat(deduplicator.checkpointOf(session)).isEmpty();
assertThat(deduplicator.replayOutcome(message(session, 1L))).isEmpty();
}
@Test
@DisplayName("only a RESUME decision carries a sequence")
void onlyResumeCarriesASequence() {
assertThat(GrpcClientStreamResumeDecision.resume(4L, "ok").resumeFromSequence()).contains(4L);
assertThat(GrpcClientStreamResumeDecision.newSession("gone").resumeFromSequence()).isEmpty();
assertThat(GrpcClientStreamResumeDecision.reject("not yours").resumeFromSequence()).isEmpty();
}
}
@@ -0,0 +1,90 @@
package dev.caskeleton.grpc.advanced.streaming;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcClientStreamPolicyTest {
@Test
@DisplayName("a dedup key includes the generation, so a resend is not mistaken for a duplicate")
void dedupKeysIncludeTheGeneration() {
GrpcClientStreamSessionId first = GrpcClientStreamSessionId.newSession();
GrpcClientStreamSessionId resumed = first.resumed();
assertThat(first.dedupKey(7L)).isNotEqualTo(resumed.dedupKey(7L));
assertThat(resumed.sameSessionAs(first)).isTrue();
assertThat(resumed.generation()).isEqualTo(2L);
}
@Test
@DisplayName("a session id and a sequence are both bounded and one-based")
void identifiersAreBounded() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
assertThat(session.generation()).isEqualTo(1L);
assertThatThrownBy(() -> session.dedupKey(0L)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new GrpcClientStreamSessionId("", 1L))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new GrpcClientStreamSessionId("s", 0L))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("a message carries its session and a one-based client sequence")
void aMessageCarriesItsPosition() {
GrpcClientStreamSessionId session = GrpcClientStreamSessionId.newSession();
GrpcClientStreamMessage<String> message = new GrpcClientStreamMessage<>(session, 3L, "payload");
assertThat(message.dedupKey()).isEqualTo(session.dedupKey(3L));
assertThatThrownBy(() -> new GrpcClientStreamMessage<>(session, 0L, "payload"))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new GrpcClientStreamMessage<>(session, 1L, null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("half-close is a state of its own, distinct from completion")
void halfCloseIsItsOwnState() {
assertThat(GrpcClientStreamState.OPEN.acceptsMessages()).isTrue();
assertThat(GrpcClientStreamState.HALF_CLOSED.acceptsMessages()).isFalse();
assertThat(GrpcClientStreamState.HALF_CLOSED.terminal()).isFalse();
assertThat(GrpcClientStreamState.COMPLETED.terminal()).isTrue();
assertThat(GrpcClientStreamState.CANCELLED.terminal()).isTrue();
}
@Test
@DisplayName("a whole client stream is never transparently retried")
void aClientStreamIsNeverWhollyRetried() {
assertThat(GrpcClientStreamPolicy.standard().wholeStreamRetryAllowed()).isFalse();
}
@Test
@DisplayName("an unbounded client stream policy is refused")
void anUnboundedClientStreamIsRefused() {
assertThatThrownBy(
() -> new GrpcClientStreamPolicy(Duration.ZERO, Duration.ofSeconds(1), 10, 10))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(
() -> new GrpcClientStreamPolicy(Duration.ofMinutes(1), Duration.ofMinutes(5), 10, 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("never fires");
assertThatThrownBy(
() -> new GrpcClientStreamPolicy(Duration.ofMinutes(5), Duration.ofSeconds(30), 0, 10))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("the standard policy bounds duration, idle, rate and in-flight together")
void theStandardPolicyBoundsEverything() {
GrpcClientStreamPolicy standard = GrpcClientStreamPolicy.standard();
assertThat(standard.maxDuration()).isEqualTo(Duration.ofMinutes(10));
assertThat(standard.idleTimeout()).isEqualTo(Duration.ofSeconds(30));
assertThat(standard.maxMessagesPerSecond()).isPositive();
assertThat(standard.maxInFlightMessages()).isPositive();
}
}
@@ -0,0 +1,101 @@
package dev.caskeleton.grpc.advanced.streaming;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcDemandControllerTest {
private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z");
@Test
@DisplayName("manual flow control is granted per method and needs a demand ceiling")
void manualFlowControlIsGrantedPerMethod() {
assertThatThrownBy(() -> new GrpcManualFlowControlPolicy(16, Duration.ofSeconds(30), false))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("granted per method");
assertThatThrownBy(() -> new GrpcManualFlowControlPolicy(0, Duration.ofSeconds(30), true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("unbounded buffering");
assertThatThrownBy(() -> new GrpcManualFlowControlPolicy(16, Duration.ZERO, true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("no timeout of its own");
}
@Test
@DisplayName("demand is bounded, and requesting past the ceiling is refused")
void demandIsBounded() {
GrpcDemandController controller =
new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW);
controller.request(4, NOW);
assertThat(controller.outstandingDemand()).isEqualTo(4);
assertThat(controller.demandCeiling()).isEqualTo(4);
assertThat(controller.decide(NOW, false).action()).isEqualTo(GrpcDemandDecision.Action.HOLD);
assertThatThrownBy(() -> controller.request(1, NOW))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("above the ceiling");
controller.messageReceived(NOW);
assertThat(controller.outstandingDemand()).isEqualTo(3);
assertThat(controller.decide(NOW, false).mayRequestMore()).isTrue();
}
@Test
@DisplayName("a request for fewer than one message is refused")
void aZeroRequestIsRefused() {
GrpcDemandController controller =
new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW);
assertThatThrownBy(() -> controller.request(0, NOW))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("both sides waiting past the watchdog is reported as a suspected deadlock")
void aMutualWaitIsReportedAsADeadlock() {
GrpcDemandController controller =
new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW);
assertThat(controller.decide(NOW.plusSeconds(29), true).action())
.isEqualTo(GrpcDemandDecision.Action.REQUEST_MORE);
GrpcDemandDecision deadlocked = controller.decide(NOW.plusSeconds(30), true);
assertThat(deadlocked.action()).isEqualTo(GrpcDemandDecision.Action.DEADLOCK_SUSPECTED);
assertThat(deadlocked.reason()).contains("will never progress");
assertThat(controller.decide(NOW.plusSeconds(30), false).mayRequestMore()).isTrue();
}
@Test
@DisplayName("activity postpones the watchdog")
void activityPostponesTheWatchdog() {
GrpcDemandController controller =
new GrpcDemandController(GrpcManualFlowControlPolicy.forApprovedMethod(4), NOW);
controller.messageReceived(NOW.plusSeconds(20));
assertThat(controller.decide(NOW.plusSeconds(40), true).action())
.isEqualTo(GrpcDemandDecision.Action.REQUEST_MORE);
}
@Test
@DisplayName("the controller never exposes a raw observer")
void theControllerExposesNoRawObserver() {
assertThat(GrpcDemandController.class.getMethods())
.extracting(java.lang.reflect.Method::getReturnType)
.extracting(Class::getName)
.noneMatch(name -> name.startsWith("io.grpc."));
}
@Test
@DisplayName("a demand decision always explains itself and carries a non-negative demand")
void aDecisionExplainsItself() {
assertThatThrownBy(() -> new GrpcDemandDecision(GrpcDemandDecision.Action.HOLD, 1, " "))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new GrpcDemandDecision(GrpcDemandDecision.Action.HOLD, -1, "why"))
.isInstanceOf(IllegalArgumentException.class);
}
}
@@ -0,0 +1,28 @@
edition = "2024";
package caskeleton.grpc.edition.v1;
option java_multiple_files = true;
option java_package = "caskeleton.grpc.edition.v1.generated";
// The Edition 2024 comparison fixture.
//
// It exists to be compiled beside its proto3 twin and compared: same fields, same numbers, same JSON
// names, with presence expressed by the edition's features rather than by `optional`. The lane's
// question is whether the two produce the same wire bytes and the same JSON, and answering it needs
// both files to exist.
//
// Not a Stable contract source. No public service moves onto an edition until the lane has produced
// cross-consumer compile evidence and a promotion ADR (GrpcEdition2024Policy.promotionApproved).
message DocumentSummary {
string id = 1;
string title = 2 [features.field_presence = EXPLICIT];
int64 revision = 3;
repeated string labels = 4;
}
enum DocumentState {
DOCUMENT_STATE_UNSPECIFIED = 0;
DOCUMENT_STATE_DRAFT = 1;
DOCUMENT_STATE_PUBLISHED = 2;
}
@@ -0,0 +1,24 @@
{
"_comment": [
"What CSDS reports for one client, as the diagnostics layer receives it before redaction.",
"The fixture deliberately contains three things a snapshot must not publish - a control-plane",
"token, a peer certificate and a raw socket address - so the redactor is tested against data",
"shaped like the real thing rather than against a string somebody invented for the assertion."
],
"version_info": "v7",
"resources": {
"documents-cluster": "v7",
"documents-route": "v7",
"documents-listener": "v6"
},
"connectivityState": "READY",
"subchannelCount": 3,
"sockets": [
{ "remoteAddress": "10.4.13.201:9090", "state": "READY" },
{ "remoteAddress": "10.4.19.87:9090", "state": "READY" },
{ "remoteAddress": "10.5.2.44:9090", "state": "TRANSIENT_FAILURE" }
],
"controlPlaneToken": "must-not-appear-in-a-snapshot",
"peerCertificate": "-----BEGIN CERTIFICATE----- must-not-appear-in-a-snapshot",
"lastCallMetadata": "x-tenant=acme"
}
+195
View File
@@ -0,0 +1,195 @@
# grpc — local authority for the gRPC platform family
이 문서는 `grpc:*` family의 **local authority**다. gRPC platform은 기본 application build와 분리된
`src/platforms/optional-build` 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](../../../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` 「템플릿 재사용 체크리스트」에 있다.
### 공용 다이제스트 헬퍼를 복사해 두는 이유
`grpc-runtime`(`GrpcRequestFingerprint`, `GrpcResumeTokenCodec`)은 SHA-256·HMAC-SHA256 계산을 자기
안에 둔다. 템플릿의 `shared-contract` `digest/Sha256`·`HmacSha256`을 쓰지 않는 것은 의도다. 이
family는 optional build에 있는 vendored 플랫폼이고 registry edge는 `grpc:*` 안에서만 닫힌다(위 표).
`shared-contract` edge를 주면 플랫폼이 템플릿 계약 leaf에 묶여 따로 떼어 쓸 수 없게 된다 — messaging
family가 같은 이유로 고른 배치(2026-08-14 messaging 모듈 리뷰 뒤 소유자가 정함)와 같다. 복사본을 고칠 때는 `shared-contract`의 정본과
같은 규칙인지 함께 본다.
## 증거 등급 — testkit이 하나의 leaf인 이유
원본 계획은 testkit을 core/in-process/netty/fault 4개 모듈로 쪼갠다. 목적은 "in-process 결과를
네트워크 증거로 오해하지 않게 한다"이고, 이 저장소는 그 목적을 모듈 경계가 아니라 **strict test
lane**으로 표현한다(`ca.strict-test-lane`: lane은 아무것도 실행하지 않으면 실패하고 up-to-date
결과를 제공하지 않는다).
`grpc-testkit`의 네 lane과 그 태그:
| lane | 태그 | 증명하는 것 |
| --- | --- | --- |
| `grpcInProcessContractTest` | `grpc-inprocess` | adapter, interceptor 순서, status, validation, idempotency replay |
| `grpcNettyContractTest` | `grpc-netty` | 실제 소켓 위의 HTTP/2, TLS/mTLS, metadata·message hard limit, GOAWAY, drain |
| `grpcFaultTest` | `grpc-fault` | 각 증거 경계에서의 연결 손실, completion unknown, partial stream |
| `grpcPerformanceTest` | `grpc-performance` | latency percentile, saturation, drain budget |
lane 분리만으로는 리포트가 잘못된 run을 인용하는 것을 막지 못하므로 `GrpcEvidenceGrade`가 런타임
체크로 이를 붙든다: `CONTRACT` 등급으로 `tls`를 주장하면 예외다.
**performance lane은 기본 `test`에서 제외된다**(leaf `build.gradle`). 공유 CI runner에서의 측정은
release path의 flaky gate가 되고, flaky gate는 꺼진다.
## Stable 범위
Stable RPC 유형은 **Unary와 Server Streaming뿐**이다. Client Streaming, Bidirectional Streaming,
hedging, xDS, custom resolver/LB, gRPC-Web, Servlet, Reactor, Kotlin은 전부 `grpc-advanced:*`이며
capability flag 뒤에 있다. `GrpcPlatformStartupValidator`가 Stable catalog에 streaming method가
등록되면 startup을 거부한다.
`grpc-spring-boot-starter`는 어떤 advanced module도 참조하지 않는다. registry의
`allowed_dependencies`와 `verifyCleanArchitectureDependencies`가 이를 build time에 강제한다.
## Optional build에 있다는 것의 의미
`grpc:*`와 `grpc-advanced:*`는 기본 `ca-skeleton` settings에 include되지 않는다. 따라서 일반
`:app-bootstrap:build`는 이 project들을 configure하지 않는다(목록은 registry의 `"build": "optional-grpc"`). 플랫폼 자체는
`./gradlew -p platforms/optional-build ci`로 검증하고, application runtime에 실제 채택하려면 composition root가
명시적으로 dependency를 가져오는 별도 변경이 필요하다.
런타임 포함 여부와 qualification은 별개다. in-process·Netty·fault lane이 통과해도 실제 배포 환경의
soak/performance baseline을 자동으로 의미하지 않는다. 지원 범위는 release gate와 support matrix가
별도로 정의한다.
## application이 이 family에 도달하는 경로
`messaging:*`가 겪은 bridge 부재(2026-08-14 messaging 모듈 리뷰)를 반복하지 않는 것이 이 family의 목표다. 계약상의 경로는
```text
application-owned port → adapter:inbound:grpc (typed service adapter) → :grpc:grpc-runtime SPI
```
이고 `GrpcServiceAdapter`가 그 SPI를 소유한다. inbound adapter가 outbound adapter·persistence에
직접 닿지 않는 규칙은 app-bootstrap ArchUnit(`INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS`)이
검사한다. 현재 `adapter:inbound:grpc`는 이 family에 의존하지 않는다 — registry의
`allowed_dependencies`를 보라. 배선은 별도 결정이며, 그때 registry edge와 브리지가 함께 들어간다.
starter가 `operation-ledger-enabled=true`일 때 멱등성 판단 bean을 조립하는 것(03-11)은 이 배선이 아니다 —
starter는 서버를 만들지 않고, 그 bean을 서버에 붙이는 일은 채택하는 쪽의 몫이다(아래 「Durable operation
ledger adoption」).
## 테스트 명령
focused test는 registry의 `gradle_path`에서 파생한다.
```bash
cd src
./gradlew -p platforms/optional-build :grpc:<leaf>:test --console=plain
./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcInProcessContractTest --console=plain
./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcNettyContractTest --console=plain
./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcFaultTest --console=plain
./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcPerformanceTest --console=plain
```
## 금지
- `grpc-core-api`에서 io.grpc / Spring / protobuf / JPA 타입 사용.
- Stable leaf에서 `:grpc-advanced:*` 참조.
- `grpc-testkit`을 production leaf가 의존하는 것.
- in-process 결과로 transport capability를 주장하는 것 (`GrpcEvidenceGrade`가 거부한다).
- metric tag에 raw metadata·payload·actor/tenant/object/stream/idempotency 식별자를 넣는 것
(`GrpcMetricCardinalityPolicy`가 거부한다).
### 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, V003 claim attempt), 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 (option (b)), and not (a).** The 2026-11-01 maturity review proposed (a):
delete the flag and judge by whether a ledger bean exists. (b) was chosen on 2026-11-03 and is recorded in
ADR-GRPC-004: 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. Both record calls take the `GrpcClaimToken`
the `PROCEED` decision carried: a commit by an attempt whose claim was taken over is refused (its
transaction rolls back) and its failure is ignored, so a slow owner cannot write over the attempt that
took its claim (ADR-GRPC-004).
**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.
+22
View File
@@ -0,0 +1,22 @@
# Buf module configuration for the Stable gRPC schema.
#
# Buf owns lint and breaking-change policy for src/main/proto; protoc (the Gradle protobuf plugin in
# build.gradle) owns compilation. CI runs both `buf lint` and `buf breaking` from this directory —
# see the `grpc-proto-buf` job in .github/workflows/ci-quality-gates.yml.
#
# cd src/platforms/grpc/grpc-contract
# buf lint
# buf breaking --against '<baseline>#subdir=src/platforms/grpc/grpc-contract'
#
# No dependencies: the only imports are protoc's own well-known types (google/protobuf/*.proto).
version: v2
modules:
- path: src/main/proto
lint:
use:
- STANDARD
breaking:
# FILE, not WIRE or WIRE_JSON. Wire compatibility alone would let a field rename or a Java package
# move through as "compatible" while every generated consumer stops compiling.
use:
- FILE
@@ -0,0 +1,47 @@
plugins {
id 'ca.platform-module'
alias(libs.plugins.protobuf)
}
// The Stable schema: the `.proto` sources under src/main/proto and the Java that protoc generates
// from them.
//
// protoc, not a hand-written parser, decides whether the schema is valid, and Buf (buf.yaml next to
// this file) owns lint and breaking-change policy. Buf runs in CI — `.github/workflows/
// ci-quality-gates.yml` job `grpc-proto-buf` — because it is a native binary and not a Maven
// artifact; this build does not re-implement its rules. Until 2026-09-28 this leaf was
// grpc-proto-contract + grpc-codegen, which did both with regular expressions (owner decision 18).
//
// Generated code lands under build/, in the package each file's `java_package` names
// (`caskeleton.*.generated`), which is disjoint from the hand-written `dev.caskeleton` root.
// Messages only: the schema declares no service yet, so there is no grpc-java stub to generate.
dependencies {
// api: every generated message extends com.google.protobuf.GeneratedMessageV3.
api libs.protobuf.java.grpc
}
protobuf {
protoc {
artifact = libs.protoc.get().toString()
}
}
// The plugin resolves protoc through a configuration it creates when generateProto runs, after
// resolveAndLockAll has taken its snapshot. The coordinate is an exact catalog version (libs.protoc),
// so a lock entry would restate it; locking is switched off for that tool locator only.
configurations.matching { it.name.startsWith('protobufToolsLocator_') }.configureEach {
resolutionStrategy.deactivateDependencyLocking()
}
// Generated sources answer to protoc, not to the repository's formatter, lint or bug patterns.
spotless {
java {
target 'src/*/java/**/*.java'
}
}
tasks.named('checkstyleMain') {
exclude '**/generated/**'
}
tasks.withType(JavaCompile).configureEach {
options.errorprone.excludedPaths = '.*/build/generated/.*'
}
@@ -0,0 +1,85 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
com.google.code.gson:gson:2.13.2=spotbugs
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:3.25.5=compileClasspath,compileProtoPath,runtimeClasspath,testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.commons:commons-text:1.3=checkstyle
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testCompileProtoPath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testCompileProtoPath,testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.mockito:mockito-core:5.20.0=mockitoAgent
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testCompileProtoPath,testRuntimeClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
empty=protobuf,testProtobuf
@@ -0,0 +1,67 @@
syntax = "proto3";
package caskeleton.grpc.common.v1;
option java_multiple_files = true;
option java_package = "caskeleton.grpc.common.v1.generated";
option java_outer_classname = "ErrorProto";
import "google/protobuf/duration.proto";
// The platform's allowlisted rich error details.
//
// Deliberately this repository's own messages rather than google.rpc.*: the Stable contract is that
// a client branches on a code, a reason and a typed detail — never on a message string — and owning
// the detail types is what keeps that surface reviewable. The shapes mirror google.rpc so a future
// move onto the common protos is a rename rather than a redesign.
// Why a request was refused before it reached a use case.
message FieldViolation {
// Fully qualified field path, e.g. "document.title".
string field = 1;
// Stable machine-readable reason, e.g. "LENGTH_EXCEEDED".
string reason = 2;
// Human-readable description. Never echoes the rejected value.
optional string description = 3;
}
// The transport validator's verdict.
message BadRequest {
repeated FieldViolation field_violations = 1;
}
// Whether and when the caller may try again. The only channel for a retry hint.
message RetryInfo {
// Delay before the next attempt. Zero duration means "do not retry".
google.protobuf.Duration retry_delay = 1;
// Attempts already made, 1-based.
int32 attempt = 2;
}
// A stable classification a client may branch on.
message ErrorInfo {
// Stable reason constant, e.g. "IDEMPOTENCY_KEY_REQUIRED".
string reason = 1;
// The service that produced the failure.
string domain = 2;
// Opaque execution id an operator can correlate. Never a stack trace or a driver message.
optional string execution_id = 3;
}
// The state that made the operation impossible.
message PreconditionFailure {
message Violation {
string type = 1;
string subject = 2;
}
repeated Violation violations = 1;
}
// What the caller may conclude about a state-changing call.
enum CompletionOutcome {
COMPLETION_OUTCOME_UNSPECIFIED = 0;
COMPLETION_OUTCOME_COMPLETED = 1;
COMPLETION_OUTCOME_REJECTED = 2;
COMPLETION_OUTCOME_COMPLETION_UNKNOWN = 3;
COMPLETION_OUTCOME_PARTIAL_STREAM = 4;
}
@@ -0,0 +1,57 @@
syntax = "proto3";
package caskeleton.grpc.common.v1;
option java_multiple_files = true;
option java_package = "caskeleton.grpc.common.v1.generated";
option java_outer_classname = "StreamProto";
// The Stable server-streaming envelope.
//
// Every Stable server stream carries these fields around its payload, because resume, gap detection
// and drain all need a position and a generation, and a stream that ships payloads alone can offer
// none of them.
// Why a stream ended.
enum StreamTerminationReason {
STREAM_TERMINATION_REASON_UNSPECIFIED = 0;
STREAM_TERMINATION_REASON_COMPLETED = 1;
STREAM_TERMINATION_REASON_CLIENT_CANCELLED = 2;
STREAM_TERMINATION_REASON_IDLE_TIMEOUT = 3;
STREAM_TERMINATION_REASON_MAX_DURATION = 4;
STREAM_TERMINATION_REASON_SERVER_DRAIN = 5;
STREAM_TERMINATION_REASON_SLOW_CONSUMER = 6;
STREAM_TERMINATION_REASON_CREDENTIAL_EXPIRED = 7;
STREAM_TERMINATION_REASON_FULL_RESYNC_REQUIRED = 8;
}
// What a stream message is.
enum StreamMessageKind {
STREAM_MESSAGE_KIND_UNSPECIFIED = 0;
STREAM_MESSAGE_KIND_SNAPSHOT = 1;
STREAM_MESSAGE_KIND_SNAPSHOT_COMPLETE = 2;
STREAM_MESSAGE_KIND_LIVE = 3;
STREAM_MESSAGE_KIND_HEARTBEAT = 4;
STREAM_MESSAGE_KIND_TERMINATION = 5;
}
// The envelope every Stable server-stream message carries.
message StreamEnvelope {
// Opaque stream identity. Never used as a metric label.
string stream_id = 1;
// Monotonic within one stream generation. Restarts only on a new generation.
uint64 sequence = 2;
// The snapshot this stream is consistent with. Distinct from the resume cursor.
optional string snapshot_version = 3;
// Opaque, signed continuation handle. Absent when the stream is not resumable.
optional string resume_token = 4;
StreamMessageKind kind = 5;
// Set only on a terminal message.
optional StreamTerminationReason termination_reason = 6;
}
// A liveness signal. Explicitly not an application acknowledgement and not an ordering guarantee.
message StreamHeartbeat {
StreamEnvelope envelope = 1;
int64 server_time_unix_millis = 2;
}
@@ -0,0 +1,46 @@
package dev.caskeleton.grpc.contract;
import static org.assertj.core.api.Assertions.assertThat;
import caskeleton.grpc.common.v1.generated.StreamEnvelope;
import caskeleton.grpc.common.v1.generated.StreamMessageKind;
import caskeleton.grpc.common.v1.generated.StreamTerminationReason;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcContractGeneratedCodeTest {
@Test
@DisplayName("protoc가 생성한 stream envelope은 wire bytes로 왕복하고 명시적 presence를 유지한다")
void generatedStreamEnvelopeRoundTripsThroughWireBytesKeepingExplicitPresence() throws Exception {
// given
StreamEnvelope sent =
StreamEnvelope.newBuilder()
.setStreamId("stream-1")
.setSequence(7L)
.setKind(StreamMessageKind.STREAM_MESSAGE_KIND_TERMINATION)
.setTerminationReason(StreamTerminationReason.STREAM_TERMINATION_REASON_SERVER_DRAIN)
.build();
// when
StreamEnvelope received = StreamEnvelope.parseFrom(sent.toByteArray());
// then
assertThat(received).isEqualTo(sent);
assertThat(received.hasTerminationReason()).isTrue();
assertThat(received.hasResumeToken()).isFalse();
}
@Test
@DisplayName("생성 코드의 proto 패키지와 Java 패키지는 조직 이름 caskeleton 아래에 있고 손으로 쓴 dev.caskeleton과 겹치지 않는다")
void generatedCodeLivesUnderTheCaskeletonProtoPackageAndOutsideTheHandWrittenRoot() {
// when
String protoPackage = StreamEnvelope.getDescriptor().getFile().getPackage();
// then
assertThat(protoPackage).isEqualTo("caskeleton.grpc.common.v1");
assertThat(StreamEnvelope.class.getPackageName())
.isEqualTo("caskeleton.grpc.common.v1.generated")
.doesNotStartWith("dev.caskeleton");
}
}
@@ -0,0 +1,18 @@
plugins {
id 'ca.platform-module'
id 'java-test-fixtures'
}
// The platform's port layer: identifiers, method policy, execution evidence, failure model,
// deadline primitives and request context.
//
// No dependencies at all, and that is the contract rather than an accident. The Stable plan's
// Global Constraints make `grpc-core-api` framework-free so "evidence and policy do not know about
// a transport" is verifiable instead of aspirational — the same rule `messaging-core-api` holds.
// A type here may not name io.grpc, Spring, Netty, protobuf or a database.
dependencies {
// Test fixtures only, never main: the operation-ledger fake and the contract that both it and
// the JPA adapter must pass, so the fake cannot allow a transition the database refuses.
testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api'
testFixturesImplementation 'org.assertj:assertj-core'
}
@@ -0,0 +1,84 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
com.google.code.gson:gson:2.13.2=spotbugs
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.commons:commons-text:1.3=checkstyle
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.mockito:mockito-core:5.20.0=mockitoAgent
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
empty=compileClasspath,runtimeClasspath
@@ -0,0 +1,55 @@
package dev.caskeleton.grpc.api.context;
/**
* Who is calling, as established by authentication — never as claimed by a header.
*
* <p>There is no factory that takes raw metadata, and that absence is the design. A tenant id read
* from an inbound header is an assertion by the caller; treating it as identity is how one tenant
* reads another's data. The only way to build this type is to name the authentication source that
* verified it.
*/
public record GrpcClientIdentity(String actorId, String tenantId, String authenticationSource) {
/** Requires bounded values and a named verifier. */
public GrpcClientIdentity {
requireBounded(actorId, "actor id");
requireBounded(tenantId, "tenant id");
requireBounded(authenticationSource, "authentication source");
}
private static void requireBounded(String value, String what) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(what + " must not be blank");
}
if (value.length() > 128) {
throw new IllegalArgumentException(what + " must be at most 128 characters");
}
for (int index = 0; index < value.length(); index++) {
if (Character.isISOControl(value.charAt(index))) {
throw new IllegalArgumentException(what + " must not contain a control character");
}
}
}
/**
* The only constructor a transport is allowed to reach.
*
* @param authenticationSource the verifier that established this identity — a token issuer, an
* mTLS peer certificate subject, an internal service credential. Naming it is what makes an
* audit able to answer "on what basis did we believe this".
*/
public static GrpcClientIdentity fromVerifiedAuthentication(
String actorId, String tenantId, String authenticationSource) {
return new GrpcClientIdentity(actorId, tenantId, authenticationSource);
}
/**
* The anonymous caller, for methods that allow one.
*
* <p>Explicit rather than null, so "no identity" and "identity not yet resolved" are different
* states in the code that reads them.
*/
public static GrpcClientIdentity anonymous() {
return new GrpcClientIdentity("anonymous", "public", "anonymous-access-policy");
}
}
@@ -0,0 +1,67 @@
package dev.caskeleton.grpc.api.context;
import dev.caskeleton.grpc.api.policy.GrpcTransportLimits;
import java.util.Map;
/**
* Two budgets, not one: the transport's hard total, and the softer allowance for keys this
* application defines.
*
* <p>They are separate because they fail differently. Exceeding the hard total is a transport
* rejection that arrives as an opaque {@code RESOURCE_EXHAUSTED} from the framework with no
* indication of which header was to blame; exceeding the user-defined allowance is this platform's
* own decision, made before the call starts, with the offending key in the message. Merging them
* would mean discovering the first kind at the point where only the second kind is fixable.
*/
public record GrpcMetadataBudget(int maxTotalBytes, int maxUserDefinedBytes, int maxEntries) {
/** Rejects an incoherent budget. */
public GrpcMetadataBudget {
if (maxTotalBytes <= 0 || maxUserDefinedBytes <= 0 || maxEntries <= 0) {
throw new IllegalArgumentException("every metadata budget bound must be positive");
}
if (maxUserDefinedBytes > maxTotalBytes) {
throw new IllegalArgumentException(
"user-defined allowance "
+ maxUserDefinedBytes
+ " cannot exceed the hard total "
+ maxTotalBytes);
}
}
/** The platform default: 8 KiB total, 4 KiB of it user-defined, at most 32 entries. */
public static GrpcMetadataBudget standard() {
return new GrpcMetadataBudget(GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, 4096, 32);
}
/**
* Checks a proposed metadata set before the call starts.
*
* @throws IllegalArgumentException naming the bound that was exceeded
*/
public void check(Map<GrpcMetadataKey, String> metadata) {
if (metadata == null) {
throw new IllegalArgumentException("metadata must not be null");
}
if (metadata.size() > maxEntries) {
throw new IllegalArgumentException(
"metadata has " + metadata.size() + " entries; the budget allows " + maxEntries);
}
int userDefinedBytes = 0;
for (Map.Entry<GrpcMetadataKey, String> entry : metadata.entrySet()) {
String value = entry.getValue();
if (value == null) {
throw new IllegalArgumentException(
"metadata key '" + entry.getKey().name() + "' has a null value");
}
userDefinedBytes += entry.getKey().name().length() + value.length();
}
if (userDefinedBytes > maxUserDefinedBytes) {
throw new IllegalArgumentException(
"user-defined metadata is "
+ userDefinedBytes
+ " bytes; the budget allows "
+ maxUserDefinedBytes);
}
}
}
@@ -0,0 +1,65 @@
package dev.caskeleton.grpc.api.context;
import java.util.regex.Pattern;
/**
* A metadata key the platform is willing to carry.
*
* <p>The {@code grpc-} prefix is refused outright: it is reserved by the protocol, and a
* user-defined key that borrows it is a key whose meaning changes when the library is upgraded. The
* {@code -bin} suffix rule is not cosmetic either — gRPC decides base64 handling from it, so a
* binary key without the suffix is a value that arrives corrupted rather than one that arrives
* mislabelled.
*/
public record GrpcMetadataKey(String name, Kind kind) {
/** Whether the value travels as ASCII text or as base64-encoded bytes. */
public enum Kind {
/** Printable ASCII value. */
ASCII,
/** Binary value; the key must end in {@code -bin}. */
BINARY
}
private static final Pattern CANONICAL = Pattern.compile("[a-z0-9]([a-z0-9._-]*[a-z0-9])?");
private static final String BINARY_SUFFIX = "-bin";
private static final String RESERVED_PREFIX = "grpc-";
/** Validates the name against the protocol's rules and this platform's allowlist shape. */
public GrpcMetadataKey {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("metadata key must not be blank");
}
if (kind == null) {
throw new IllegalArgumentException("metadata key needs a kind");
}
if (name.length() > 64) {
throw new IllegalArgumentException("metadata key must be at most 64 characters: " + name);
}
if (!CANONICAL.matcher(name).matches()) {
throw new IllegalArgumentException(
"metadata key must be lowercase and use only [a-z0-9._-]: " + name);
}
if (name.startsWith(RESERVED_PREFIX)) {
throw new IllegalArgumentException(
"metadata key '" + name + "' uses the reserved 'grpc-' prefix");
}
boolean binarySuffix = name.endsWith(BINARY_SUFFIX);
if (kind == Kind.BINARY && !binarySuffix) {
throw new IllegalArgumentException("binary metadata key must end in '-bin': " + name);
}
if (kind == Kind.ASCII && binarySuffix) {
throw new IllegalArgumentException("ASCII metadata key must not end in '-bin': " + name);
}
}
/** An ASCII key. */
public static GrpcMetadataKey ascii(String name) {
return new GrpcMetadataKey(name, Kind.ASCII);
}
/** A binary key. */
public static GrpcMetadataKey binary(String name) {
return new GrpcMetadataKey(name, Kind.BINARY);
}
}
@@ -0,0 +1,87 @@
package dev.caskeleton.grpc.api.context;
import dev.caskeleton.grpc.api.deadline.GrpcCancellationToken;
import dev.caskeleton.grpc.api.deadline.GrpcDeadlineBudget;
import dev.caskeleton.grpc.core.GrpcMethodName;
import dev.caskeleton.grpc.core.RpcType;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* What an application use case is handed when a gRPC call reaches it.
*
* <p>Notice what is not here: no {@code Metadata}, no credentials, no headers map. The metadata
* that survives is the allowlisted subset, keyed by a validated {@link GrpcMetadataKey}, and the
* allowlist is supplied at construction rather than consulted from a global — so a test can state
* the allowlist it means and a second transport cannot quietly widen it.
*/
public record GrpcRequestContext(
GrpcMethodName method,
RpcType rpcType,
GrpcClientIdentity identity,
GrpcDeadlineBudget deadline,
GrpcCancellationToken cancellation,
Map<GrpcMetadataKey, String> metadata,
Optional<String> traceId) {
/** Copies the metadata map so the context cannot change after the call has started. */
public GrpcRequestContext {
if (method == null
|| rpcType == null
|| identity == null
|| deadline == null
|| cancellation == null
|| metadata == null
|| traceId == null) {
throw new IllegalArgumentException("request context fields must all be present");
}
metadata = Map.copyOf(metadata);
}
/**
* Builds a context from inbound metadata, keeping only allowlisted keys.
*
* <p>Unknown keys are refused rather than dropped. Silently dropping is worse: the caller
* believes it sent a correlation id, the server never sees one, and nothing anywhere says so.
*
* @throws IllegalArgumentException when a key is outside {@code allowlist}, or the budget is
* exceeded
*/
public static GrpcRequestContext create(
GrpcMethodName method,
RpcType rpcType,
GrpcClientIdentity identity,
GrpcDeadlineBudget deadline,
GrpcCancellationToken cancellation,
Map<GrpcMetadataKey, String> inboundMetadata,
Set<GrpcMetadataKey> allowlist,
GrpcMetadataBudget budget,
String traceId) {
if (inboundMetadata == null || allowlist == null || budget == null) {
throw new IllegalArgumentException("metadata, allowlist and budget must all be present");
}
Map<GrpcMetadataKey, String> accepted = new LinkedHashMap<>();
for (Map.Entry<GrpcMetadataKey, String> entry : inboundMetadata.entrySet()) {
if (!allowlist.contains(entry.getKey())) {
throw new IllegalArgumentException(
"metadata key '" + entry.getKey().name() + "' is not on this method's allowlist");
}
accepted.put(entry.getKey(), entry.getValue());
}
budget.check(accepted);
return new GrpcRequestContext(
method, rpcType, identity, deadline, cancellation, accepted, Optional.ofNullable(traceId));
}
/** An allowlisted metadata value, if the caller sent one. */
public Optional<String> metadataValue(GrpcMetadataKey key) {
return Optional.ofNullable(metadata.get(key));
}
/** Whether the call is still worth doing work for. */
public boolean live() {
return !cancellation.cancelled() && !deadline.expired();
}
}
@@ -0,0 +1,68 @@
package dev.caskeleton.grpc.api.deadline;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
/**
* An idempotent cancellation signal that remembers why it first fired.
*
* <p>"First reason wins" is the contract that makes a cancellation report usable. A call cancelled
* by its client and then, a millisecond later, by a shutdown drain has one cause and one useful
* story; a token that keeps the last write tells the second one.
*/
public final class GrpcCancellationToken {
private final AtomicReference<Cancellation> cancellation = new AtomicReference<>();
/** The reason and moment a token fired. */
public record Cancellation(String reason, Instant at) {
/** Requires a bounded reason and a moment. */
public Cancellation {
if (reason == null || reason.isBlank() || reason.length() > 128) {
throw new IllegalArgumentException(
"cancellation reason must be a bounded non-blank string");
}
if (at == null) {
throw new IllegalArgumentException("cancellation needs a timestamp");
}
}
}
/**
* Cancels once. Later calls are accepted and ignored.
*
* @return true when this call is the one that cancelled the token
*/
public boolean cancel(String reason, Instant at) {
return cancellation.compareAndSet(null, new Cancellation(reason, at));
}
/** Whether the token has fired. */
public boolean cancelled() {
return cancellation.get() != null;
}
/** The first cancellation, if any. */
public Optional<Cancellation> cancellation() {
return Optional.ofNullable(cancellation.get());
}
/**
* Fails when the token has already fired.
*
* <p>Called before starting a new external side effect. The Stable plan forbids beginning one
* after cancellation, and the only way to hold that is to ask at the moment of starting.
*/
public void requireNotCancelled(String operation) {
Cancellation current = cancellation.get();
if (current != null) {
throw new IllegalStateException(
"refusing to start '"
+ operation
+ "': the call was cancelled ("
+ current.reason()
+ ")");
}
}
}
@@ -0,0 +1,130 @@
package dev.caskeleton.grpc.api.deadline;
import java.time.Duration;
import java.util.function.LongSupplier;
/**
* How much time a call actually has, after the parent deadline and the method profile have both had
* their say.
*
* <p>The rule is "shorter of the two, minus the reserve", and it is here rather than at each call
* site because the failure mode of getting it wrong is silent: a downstream timeout longer than the
* inbound deadline never fires, and the caller sees a deadline the server has no idea it missed.
*
* <p>The budget is an absolute deadline on a monotonic nanosecond clock, so {@link #remaining()}
* shrinks and {@link #expired()} turns true as time passes. A request context carries one budget
* for the whole call; a budget that remembered only the duration it started with would hand every
* later dependency call the full original time.
*/
public final class GrpcDeadlineBudget {
private final long deadlineNanos;
private final GrpcDeadlineProfile profile;
private final LongSupplier nanoClock;
/** A budget of {@code remaining} from now on the system's monotonic clock. */
public GrpcDeadlineBudget(Duration remaining, GrpcDeadlineProfile profile) {
this(remaining, profile, System::nanoTime);
}
/**
* A budget of {@code remaining} from now on {@code nanoClock}.
*
* @param nanoClock a monotonic nanosecond source, {@code System::nanoTime} outside tests
*/
public GrpcDeadlineBudget(
Duration remaining, GrpcDeadlineProfile profile, LongSupplier nanoClock) {
if (remaining == null || profile == null || nanoClock == null) {
throw new IllegalArgumentException(
"a deadline budget needs a remaining time, a profile and a clock");
}
if (remaining.isNegative()) {
throw new IllegalArgumentException("remaining time must not be negative; got " + remaining);
}
this.deadlineNanos = nanoClock.getAsLong() + remaining.toNanos();
this.profile = profile;
this.nanoClock = nanoClock;
}
/**
* The budget for a Stable unary entry point, which must have a positive deadline.
*
* @throws IllegalArgumentException when there is no parent deadline at all — the Stable plan
* requires every unary method to carry one, and defaulting here is how a call ends up with an
* infinite deadline nobody chose
*/
public static GrpcDeadlineBudget forEntryPoint(
Duration parentRemaining, GrpcDeadlineProfile profile) {
return forEntryPoint(parentRemaining, profile, System::nanoTime);
}
/** {@link #forEntryPoint(Duration, GrpcDeadlineProfile)} on {@code nanoClock}. */
public static GrpcDeadlineBudget forEntryPoint(
Duration parentRemaining, GrpcDeadlineProfile profile, LongSupplier nanoClock) {
if (profile == null) {
throw new IllegalArgumentException("a deadline budget needs a profile");
}
if (parentRemaining == null) {
throw new IllegalArgumentException(
"a Stable unary call requires a positive deadline; none was propagated");
}
if (parentRemaining.isZero() || parentRemaining.isNegative()) {
throw new IllegalArgumentException(
"a Stable unary call requires a positive deadline; got " + parentRemaining);
}
return new GrpcDeadlineBudget(afterReserve(parentRemaining, profile), profile, nanoClock);
}
/**
* Derives the budget for a downstream dependency call under {@code downstream}.
*
* <p>Takes the shorter of what is left here now and what the downstream profile allows, then
* subtracts the downstream reserve. A dependency can never be given more time than its caller
* has.
*/
public GrpcDeadlineBudget deriveDownstream(GrpcDeadlineProfile downstream) {
if (downstream == null) {
throw new IllegalArgumentException("a downstream budget needs a profile");
}
return new GrpcDeadlineBudget(afterReserve(remaining(), downstream), downstream, nanoClock);
}
/** What is left now; zero once the deadline has passed. */
public Duration remaining() {
long left = deadlineNanos - nanoClock.getAsLong();
return left <= 0 ? Duration.ZERO : Duration.ofNanos(left);
}
/** The profile this budget was cut from. */
public GrpcDeadlineProfile profile() {
return profile;
}
/**
* Whether there is enough time left to be worth starting a dependency call.
*
* <p>Starting one with less is not merely wasteful: it produces a deadline failure on the
* dependency that looks identical to the dependency being slow, and the resulting incident
* investigates the wrong system.
*/
public boolean canStartDependencyCall() {
Duration left = remaining();
return !left.isZero() && left.compareTo(profile.minimumAttemptBudget()) >= 0;
}
/** Whether any time is left at all. */
public boolean expired() {
return remaining().isZero();
}
@Override
public String toString() {
return "GrpcDeadlineBudget[remaining=" + remaining() + ", profile=" + profile + "]";
}
private static Duration afterReserve(Duration available, GrpcDeadlineProfile profile) {
Duration bounded = available.compareTo(profile.total()) <= 0 ? available : profile.total();
Duration afterReserve = bounded.minus(profile.safetyMargin());
return afterReserve.isNegative() ? Duration.ZERO : afterReserve;
}
}
@@ -0,0 +1,26 @@
package dev.caskeleton.grpc.api.deadline;
import dev.caskeleton.grpc.api.error.GrpcFailureContext;
import dev.caskeleton.grpc.api.error.GrpcPlatformException;
/**
* A deadline elapsed.
*
* <p>Its own type rather than a generic platform exception because callers branch on it, and
* because it is the failure most often misread: for a mutation it is a statement about time, not
* about the outcome. {@link #requiresReconciliation()} answers the question the status code cannot.
*/
public class GrpcDeadlineExceededException extends GrpcPlatformException {
private static final long serialVersionUID = 1L;
/** Wraps a deadline failure context. */
public GrpcDeadlineExceededException(GrpcFailureContext context) {
super(context);
}
/** Wraps a deadline failure context, preserving the underlying cause. */
public GrpcDeadlineExceededException(GrpcFailureContext context, Throwable cause) {
super(context, cause);
}
}
@@ -0,0 +1,59 @@
package dev.caskeleton.grpc.api.deadline;
import java.time.Duration;
/**
* A method's deadline shape: how long it gets, how much is held back, and the smallest slice worth
* starting a dependency call with.
*
* <p>The safety margin is not decoration. A downstream call handed the parent's entire remaining
* time has no room left to serialize a response or write trailers, so the caller's deadline fires
* while the answer is in flight — which produces exactly the {@code COMPLETION_UNKNOWN} the
* platform then has to reconcile.
*/
public record GrpcDeadlineProfile(
Duration total, Duration safetyMargin, Duration minimumAttemptBudget) {
/** Rejects a profile that cannot leave usable time behind. */
public GrpcDeadlineProfile {
if (total == null || safetyMargin == null || minimumAttemptBudget == null) {
throw new IllegalArgumentException("a deadline profile needs all three durations");
}
if (total.isZero() || total.isNegative()) {
throw new IllegalArgumentException("total deadline must be positive; got " + total);
}
if (safetyMargin.isNegative()) {
throw new IllegalArgumentException("safety margin must not be negative");
}
if (minimumAttemptBudget.isNegative()) {
throw new IllegalArgumentException("minimum attempt budget must not be negative");
}
if (safetyMargin.compareTo(total) >= 0) {
throw new IllegalArgumentException(
"safety margin " + safetyMargin + " leaves no time inside total " + total);
}
if (minimumAttemptBudget.compareTo(total.minus(safetyMargin)) > 0) {
throw new IllegalArgumentException(
"minimum attempt budget "
+ minimumAttemptBudget
+ " exceeds the usable window "
+ total.minus(safetyMargin));
}
}
/**
* A profile with the platform's default reserves: a tenth of the total held back for response
* serialization and trailers, and a twentieth as the smallest attempt worth starting.
*/
public static GrpcDeadlineProfile of(Duration total) {
if (total == null || total.isZero() || total.isNegative()) {
throw new IllegalArgumentException("total deadline must be positive");
}
return new GrpcDeadlineProfile(total, total.dividedBy(10), total.dividedBy(20));
}
/** Total minus the reserve — the time actually available to the call. */
public Duration usable() {
return total.minus(safetyMargin);
}
}
@@ -0,0 +1,69 @@
package dev.caskeleton.grpc.api.error;
import dev.caskeleton.grpc.core.GrpcStatusCode;
import dev.caskeleton.grpc.evidence.GrpcBusinessEvidence;
import dev.caskeleton.grpc.evidence.GrpcExecutionEvidence;
import dev.caskeleton.grpc.evidence.GrpcStreamEvidence;
/**
* What the caller may conclude about the business operation.
*
* <p>Separate from the status code because the interesting case has no status of its own: a
* mutation that times out is {@code DEADLINE_EXCEEDED} on the wire and {@link #COMPLETION_UNKNOWN}
* in the business, and a caller that reads the first as the second's answer either loses a
* committed write or performs it twice.
*/
public enum GrpcCompletionOutcome {
/** The operation completed and the caller knows it. */
COMPLETED,
/** The operation did not run; nothing changed. */
REJECTED,
/** The operation may or may not have completed. Requires a status query or reconciliation. */
COMPLETION_UNKNOWN,
/** A stream delivered a prefix and then ended. */
PARTIAL_STREAM;
/**
* Derives the outcome from a status and the evidence, for a call that changes state.
*
* <p>{@code DEADLINE_EXCEEDED} on a mutation defaults to {@link #COMPLETION_UNKNOWN} rather than
* to a failure, and {@code UNAVAILABLE} does the same unless the client watched the send fail.
* Those two defaults are the plan's Global Constraints, in the one place that can apply them.
*/
public static GrpcCompletionOutcome forMutation(
GrpcStatusCode statusCode, GrpcExecutionEvidence evidence) {
if (statusCode == null || evidence == null) {
throw new IllegalArgumentException("outcome derivation needs a status and evidence");
}
if (evidence.business() == GrpcBusinessEvidence.COMMIT_CONFIRMED) {
return COMPLETED;
}
if (evidence.stream() instanceof GrpcStreamEvidence.Partial) {
return PARTIAL_STREAM;
}
if (statusCode == GrpcStatusCode.OK) {
return COMPLETED;
}
if (evidence.transport().provesNotStarted()) {
return REJECTED;
}
return switch (statusCode) {
case DEADLINE_EXCEEDED, UNAVAILABLE, CANCELLED, UNKNOWN, INTERNAL -> COMPLETION_UNKNOWN;
case INVALID_ARGUMENT,
UNAUTHENTICATED,
PERMISSION_DENIED,
NOT_FOUND,
FAILED_PRECONDITION,
OUT_OF_RANGE,
UNIMPLEMENTED,
RESOURCE_EXHAUSTED ->
REJECTED;
case OK, ALREADY_EXISTS, ABORTED, DATA_LOSS -> COMPLETION_UNKNOWN;
};
}
/** Whether the caller must resolve the result before acting on it. */
public boolean requiresReconciliation() {
return this == COMPLETION_UNKNOWN;
}
}
@@ -0,0 +1,64 @@
package dev.caskeleton.grpc.api.error;
import dev.caskeleton.grpc.core.GrpcStatusCode;
/**
* The platform's stable failure taxonomy, and the canonical status each category maps to.
*
* <p>The mapping lives on the category rather than in a switch somewhere in the server, because the
* client needs the same table to interpret what it received. A category whose status is decided at
* the mapping site has a different answer on each side of the wire.
*/
public enum GrpcFailureCategory {
/** Malformed request; the transport validator refused it. */
VALIDATION(GrpcStatusCode.INVALID_ARGUMENT, false),
/** No verified caller identity. */
AUTHENTICATION(GrpcStatusCode.UNAUTHENTICATED, false),
/** A verified caller without the required permission. */
AUTHORIZATION(GrpcStatusCode.PERMISSION_DENIED, false),
/** The addressed resource does not exist. */
NOT_FOUND(GrpcStatusCode.NOT_FOUND, false),
/** A uniqueness or version conflict the caller can resolve. */
CONFLICT(GrpcStatusCode.ABORTED, true),
/** The resource is in a state that forbids the operation. */
PRECONDITION(GrpcStatusCode.FAILED_PRECONDITION, false),
/** A quota, rate limit or admission bound was hit. */
RESOURCE_EXHAUSTED(GrpcStatusCode.RESOURCE_EXHAUSTED, true),
/** The deadline elapsed. Says nothing about whether the work completed. */
DEADLINE(GrpcStatusCode.DEADLINE_EXCEEDED, false),
/** The caller or the platform cancelled the call. */
CANCELLED(GrpcStatusCode.CANCELLED, false),
/** The dependency could not be reached, or refused a connection. */
TRANSIENT_DEPENDENCY(GrpcStatusCode.UNAVAILABLE, true),
/** The dependency answered with a failure that retrying will reproduce. */
PERMANENT_DEPENDENCY(GrpcStatusCode.INTERNAL, false),
/** The method exists in the schema but is not served. */
UNIMPLEMENTED(GrpcStatusCode.UNIMPLEMENTED, false),
/** Stored state is inconsistent with what the contract guarantees. */
DATA_INTEGRITY(GrpcStatusCode.DATA_LOSS, false),
/** Anything unclassified. Never carries provider detail to the client. */
INTERNAL(GrpcStatusCode.INTERNAL, false);
private final GrpcStatusCode statusCode;
private final boolean transientFailure;
GrpcFailureCategory(GrpcStatusCode statusCode, boolean transientFailure) {
this.statusCode = statusCode;
this.transientFailure = transientFailure;
}
/** The wire status this category maps to. */
public GrpcStatusCode statusCode() {
return statusCode;
}
/**
* Whether the same call, later, might succeed.
*
* <p>Necessary for a retry, never sufficient: {@code TRANSIENT_DEPENDENCY} on a non-idempotent
* mutation is still not retryable, and that decision belongs to the retry coordinator.
*/
public boolean transientFailure() {
return transientFailure;
}
}
@@ -0,0 +1,99 @@
package dev.caskeleton.grpc.api.error;
import dev.caskeleton.grpc.core.GrpcMethodName;
import dev.caskeleton.grpc.core.GrpcStatusCode;
import dev.caskeleton.grpc.evidence.GrpcExecutionEvidence;
import java.time.Duration;
import java.util.Optional;
/**
* Everything the platform is willing to say about a failed attempt.
*
* <p>The field list is a closed allowlist rather than a convenience bag. Every field here is
* bounded and safe to log; a payload, a metadata map, a token or an idempotency key has no
* component to live in, so redaction is a property of the type rather than of whoever writes the
* log line. The provider exception survives as {@code cause} on {@link GrpcPlatformException},
* where it reaches an operator without reaching a client.
*/
public record GrpcFailureContext(
GrpcMethodName method,
GrpcStatusCode statusCode,
GrpcFailureCategory category,
GrpcExecutionEvidence evidence,
GrpcCompletionOutcome completionOutcome,
RetryDisposition retryDisposition,
int attempt,
Duration elapsed,
Optional<String> traceId) {
/**
* What the platform decided about retrying this attempt, and why it is not re-derivable later.
*/
public enum RetryDisposition {
/** The attempt may be retried under the method's retry policy. */
RETRYABLE,
/** The attempt must not be retried; repeating it risks a duplicate effect. */
NOT_RETRYABLE,
/** Retrying is pointless: the same call will fail the same way. */
TERMINAL,
/** The result is unknown; resolve it with a status query before deciding. */
RESOLVE_FIRST
}
/** Validates bounds and rejects a trace id that is not safe to log. */
public GrpcFailureContext {
if (method == null
|| statusCode == null
|| category == null
|| evidence == null
|| completionOutcome == null
|| retryDisposition == null
|| elapsed == null
|| traceId == null) {
throw new IllegalArgumentException("failure context fields must all be present");
}
if (attempt < 1) {
throw new IllegalArgumentException("attempt is 1-based; got " + attempt);
}
if (elapsed.isNegative()) {
throw new IllegalArgumentException("elapsed must not be negative");
}
if (!method.equals(evidence.method())) {
throw new IllegalArgumentException(
"failure context method '"
+ method.canonical()
+ "' disagrees with its evidence '"
+ evidence.method().canonical()
+ "'");
}
traceId.ifPresent(
value -> {
if (value.isBlank() || value.length() > 128) {
throw new IllegalArgumentException("trace id must be a bounded non-blank identifier");
}
});
}
/**
* A one-line summary safe to put in an exception message, a log line or an operator report.
*
* <p>Built here rather than at each call site so there is exactly one answer to "what may this
* failure say out loud".
*/
public String redactedSummary() {
return method.canonical()
+ " failed with "
+ statusCode
+ " ("
+ category
+ "), outcome="
+ completionOutcome
+ ", retry="
+ retryDisposition
+ ", attempt="
+ attempt
+ ", elapsedMs="
+ elapsed.toMillis()
+ traceId.map(id -> ", trace=" + id).orElse("");
}
}
@@ -0,0 +1,44 @@
package dev.caskeleton.grpc.api.error;
/**
* The platform's failure carrier.
*
* <p>Its message is {@link GrpcFailureContext#redactedSummary()} and nothing else, so the string
* that ends up in a log or in a status description cannot accidentally be a driver message
* containing a SQL state, a host or a token. The original exception is kept as the cause, which is
* where an operator reads it and a client does not.
*/
public class GrpcPlatformException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final transient GrpcFailureContext context;
/** Wraps a failure context. */
public GrpcPlatformException(GrpcFailureContext context) {
this(context, null);
}
/** Wraps a failure context, preserving the provider exception as the cause. */
public GrpcPlatformException(GrpcFailureContext context, Throwable cause) {
super(requireContext(context).redactedSummary(), cause);
this.context = context;
}
private static GrpcFailureContext requireContext(GrpcFailureContext context) {
if (context == null) {
throw new IllegalArgumentException("a platform exception requires a failure context");
}
return context;
}
/** The structured failure this exception carries. */
public GrpcFailureContext context() {
return context;
}
/** Whether the caller must resolve the business result before acting. */
public boolean requiresReconciliation() {
return context.completionOutcome().requiresReconciliation();
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.grpc.api.ledger;
/**
* Which attempt holds a claim: the fencing token a commit or a failure record must present.
*
* <p>A claim can change hands. A stale one is taken over after the claim TTL, and a failed one is
* re-claimed by the next retry; both make a new attempt of the same operation. The owner that lost
* the claim may still be running, and when it finishes it records its outcome. Without a token that
* record lands on the new attempt's claim: an old owner's failure turned the new attempt's claim
* {@code FAILED_TERMINAL}, a third retry re-claimed it, and two attempts ran the mutation at once
* (re-review 2026-11-03, RR-02-04). With it, the ledger records an outcome only for the attempt
* that still holds the claim.
*
* <p>A counter rather than the claim moment: it increases by one with every hand-over, so two
* attempts of one record never share a value, whatever the clocks of the processes that claimed it.
* The counter lives in the record: once the record is deleted ({@code release}, or the purge of a
* finished record), the next claim of the key starts again at {@link #FIRST}. Both deletions are
* therefore limited to records no live attempt can still write to — a released claim's owner is
* known to be gone, and a purged record finished longer ago than any retry (review 2026-11-03
* RR-01-15).
*
* @param attempt one for the first claim of an operation, one more for each hand-over
*/
public record GrpcClaimToken(long attempt) {
/** The token of the claim that created the record. */
public static final GrpcClaimToken FIRST = new GrpcClaimToken(1);
/** Requires a positive attempt number. */
public GrpcClaimToken {
if (attempt < 1) {
throw new IllegalArgumentException("a claim attempt is numbered from one, was " + attempt);
}
}
/** The token of the attempt that takes this claim over. */
public GrpcClaimToken next() {
return new GrpcClaimToken(Math.addExact(attempt, 1));
}
}
@@ -0,0 +1,64 @@
package dev.caskeleton.grpc.api.ledger;
import dev.caskeleton.grpc.core.GrpcMethodName;
/**
* What makes two requests the same operation.
*
* <p>All three parts are load-bearing. Without the caller fingerprint, one tenant's idempotency key
* suppresses another tenant's write. Without the method, the same key reused across two operations
* makes the second one a replay of the first. Without the key, there is no operation identity at
* all.
*
* <p>The key is stored as a hash, never in the clear: an idempotency key is chosen by the caller
* and is frequently an order id, an invoice number or something else that identifies a person.
*/
public record GrpcOperationIdentity(
String callerFingerprint, GrpcMethodName method, String idempotencyKeyHash) {
// Column widths of grpc_operation_ledger (V001). An identity that does not fit is refused here,
// not by the database in the middle of a claim.
private static final int MAX_CALLER_FINGERPRINT = 256;
private static final int MAX_METHOD = 256;
private static final int MAX_KEY_HASH = 80;
private static final int MAX_STORAGE_KEY = 512;
/** Requires all three parts, with the key already hashed. */
public GrpcOperationIdentity {
if (callerFingerprint == null || callerFingerprint.isBlank()) {
throw new IllegalArgumentException(
"an operation identity needs a caller fingerprint; without one, a key from one tenant "
+ "suppresses another tenant's write");
}
if (method == null) {
throw new IllegalArgumentException("an operation identity names its method");
}
if (idempotencyKeyHash == null || !idempotencyKeyHash.startsWith("sha256:")) {
throw new IllegalArgumentException(
"the idempotency key is stored hashed; got '" + idempotencyKeyHash + "'");
}
requireAtMost("caller fingerprint", callerFingerprint, MAX_CALLER_FINGERPRINT);
requireAtMost("full method name", method.canonical(), MAX_METHOD);
requireAtMost("idempotency key hash", idempotencyKeyHash, MAX_KEY_HASH);
requireAtMost(
"storage key",
callerFingerprint + "|" + method.canonical() + "|" + idempotencyKeyHash,
MAX_STORAGE_KEY);
}
private static void requireAtMost(String what, String value, int max) {
if (value.length() > max) {
throw new IllegalArgumentException(
what
+ " must be at most "
+ max
+ " characters to fit the ledger; got "
+ value.length());
}
}
/** The stable storage key: the three parts joined, safe to index and safe to log. */
public String storageKey() {
return callerFingerprint + "|" + method.canonical() + "|" + idempotencyKeyHash;
}
}

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