diff --git a/README.md b/README.md index cbd11f3..cd6ddeb 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Optional gRPC platforms -The default application does not depend on `grpc/*` or `grpc-advanced/*`, so those 18 projects are -kept out of the main multi-project build. This build preserves their existing project paths and +The default application does not depend on `grpc/*` or `grpc-advanced/*`, so those projects (the +registry entries with `"build": "optional-grpc"`) are kept out of the main multi-project build. This build preserves their existing project paths and internal project dependencies while making their configuration opt-in. ```bash diff --git a/build.gradle b/build.gradle index 001bb2d..59808a9 100644 --- a/build.gradle +++ b/build.gradle @@ -1,16 +1,10 @@ plugins { id 'ca.architecture' - // Without it every gRPC leaf's jar is versioned 0.0.1-SNAPSHOT, because JavaConventionsPlugin - // falls back to that when the root has no ReleaseProvenanceExtension — so one commit produced - // two artifact sets under two different version schemes, and only one of them could be traced - // back to a revision. - id 'ca.release-provenance' } -ext.sourceRevision = providers.gradleProperty('gitRevision') - .orElse(providers.environmentVariable('GIT_SHA')) - .orElse(providers.environmentVariable('GITHUB_SHA')) - .getOrElse('unknown') +// No `ca.release-provenance` any more: each gRPC leaf's `ca.java-conventions` derives its version +// and `sourceRevision` from the same -PreleaseVersion/-PgitRevision (GIT_SHA, GITHUB_SHA) inputs the +// main build reads, so one commit produces one version scheme in both builds (review BUILD-O3-5). tasks.register('resolveAndLockAll') { group = 'build setup' @@ -35,7 +29,9 @@ tasks.register('ci') { description = 'Runs the optional gRPC platform verification surface.' dependsOn tasks.named('checkAll') dependsOn tasks.named('qualityCheck') - dependsOn tasks.named('verifyCleanArchitectureDependencies') + // architectureCheck, not only the direction gate: it also runs verifyNoIgnoredSourcePackages, so + // a gRPC source Git would drop fails this build's ci the way it fails the main build's. + dependsOn tasks.named('architectureCheck') } // A strict integration lane that no workflow invokes is not coverage; it is a file that looks like diff --git a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md index 560d494..5e3b523 100644 --- a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md +++ b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md @@ -1,8 +1,17 @@ # ADR-GRPC-002: Schema governance runs without protoc and without the Buf CLI -- Status: accepted +- Status: **superseded (2026-09-28)** by owner decision 18 of the 2026-09-25 review follow-up - Date: 2026-08-30 -- Scope: `:grpc:grpc-proto-contract`, `:grpc:grpc-codegen` +- Scope: `:grpc:grpc-proto-contract`, `:grpc:grpc-codegen` (both removed) + +> **Superseded.** The regex `.proto` validator and the Java re-implementation of Buf's rules were +> deleted. The schema now lives in `:grpc:grpc-contract` (`src/grpc/grpc-contract/src/main/proto`), +> compiled by the Gradle protobuf plugin (`com.google.protobuf`, version pinned in +> `src/gradle/libs.versions.toml`; protoc and the protobuf-java runtime are both `protobufGrpc`). +> Generated sources are excluded from Spotless, Checkstyle and Error Prone in that leaf only. +> `buf lint` and `buf breaking` (`src/grpc/grpc-contract/buf.yaml`, STANDARD lint, FILE breaking) +> run in CI, job `grpc-proto-buf` in `.github/workflows/ci-quality-gates.yml`. The proto organization +> is `caskeleton` (was `hyeonworks`). The text below is kept as the record of the original decision. ## Context diff --git a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md index aff2a68..e4f6d50 100644 --- a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md +++ b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md @@ -2,7 +2,7 @@ - Status: accepted - Date: 2026-08-30 -- Scope: `:grpc:grpc-core-api`, `:grpc:grpc-policy`, `:grpc:grpc-testkit` +- Scope: `:grpc:grpc-core-api`, `:grpc:grpc-runtime` (was `grpc-policy`), `:grpc:grpc-testkit` ## Context diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index dafadad..a7e2ebf 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -2,7 +2,7 @@ - Status: accepted - Date: 2026-08-30 -- Scope: `:grpc:grpc-policy`, `:grpc:grpc-operation-ledger-jpa`, `:grpc:grpc-core-api` +- Scope: `:grpc:grpc-runtime` (was `grpc-policy`), `:grpc:grpc-operation-ledger-jpa`, `:grpc:grpc-core-api` ## Context diff --git a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md index e6d885d..b648be9 100644 --- a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md +++ b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md @@ -2,7 +2,7 @@ - Status: accepted - Date: 2026-08-30 -- Scope: `:grpc:grpc-policy` +- Scope: `:grpc:grpc-runtime` (was `grpc-policy`) ## Context diff --git a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md index 135abd9..3be4e14 100644 --- a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md +++ b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md @@ -2,7 +2,7 @@ - Status: accepted - Date: 2026-08-31 -- Scope: `:grpc:grpc-discovery`, `:grpc:grpc-client` +- Scope: `:grpc:grpc-runtime` (was `grpc-discovery`, `grpc-client`) ## Context @@ -63,6 +63,6 @@ declaration is a wrong statement somebody wrote down, and a missing one is a que `GrpcChannelProfileValidator` takes resolved counts where they are known at startup and skips the check where they are not, rather than guessing and failing on a name that cannot be resolved yet. -**xDS is reachable, and not by this route.** It lives in `grpc-advanced-resilience` behind its +**xDS is reachable, and not by this route.** It lives in `grpc-advanced` (package `resilience`/`xds`) behind its capability flag and its production approval, and `GrpcXdsStartupGuard.advertisableAsStableSupport()` returns false so the Stable support statement cannot widen quietly. See ADR-GRPC-ADV-001. diff --git a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md index 004528e..041a85a 100644 --- a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md +++ b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md @@ -29,7 +29,9 @@ production unapproved — because the remedy differs in each case. **Promotion evidence is per capability.** `GrpcAdvancedPromotionEvidence` is one record per capability, so no promotion can drag another along; `GrpcAdvancedPromotionGate.capabilitiesDraggedAlong` returns an empty list, and that is a tested -property rather than a claim. Two thresholds: seven days of soak plus complete evidence for +property rather than a claim. (2026-09-28: the gate classes were removed because nothing outside +their own tests called them — review 2026-09-24 S5-lead-4. The per-capability rule stands as a +review rule in `docs/runbooks/grpc-advanced-capabilities.md`.) Two thresholds: seven days of soak plus complete evidence for `ADVANCED_STABLE`, thirty for a Stable default, because the second means every deployment gets the capability's dependencies and its failure modes. diff --git a/docs/compatibility/grpc-advanced-support-matrix.md b/docs/compatibility/grpc-advanced-support-matrix.md index b3cf491..9df35cb 100644 --- a/docs/compatibility/grpc-advanced-support-matrix.md +++ b/docs/compatibility/grpc-advanced-support-matrix.md @@ -4,7 +4,7 @@ Every capability in `:grpc-advanced:*`, its grade, and what it would take to rai `GrpcAdvancedSupportMatrix` is the machine-readable form; `GrpcAdvancedCapability.defaultGrade` carries the same values. -All capabilities are off by default. Flags are `ca-skeleton.grpc.advanced..enabled`. +All capabilities are off by default. Flags are `app.grpc.advanced..enabled`. ## Grades @@ -29,7 +29,7 @@ All capabilities are off by default. Flags are `ca-skeleton.grpc.advanced. **2026-09-28 변경(리뷰 후속 S7-#3·S7-#13, 소유자 결정 18).** 아래 두 표는 채택 당시의 leaf 구성이다. +> 현재는 `grpc-policy`·`grpc-server`·`grpc-client`·`grpc-discovery`·`grpc-admin` → `grpc-runtime`, +> `grpc-proto-contract`·`grpc-codegen` → `grpc-contract`(protobuf Gradle 플러그인 + CI의 Buf, D5/D6 폐기 — +> ADR-GRPC-002 superseded), `grpc-advanced-bootstrap`·`-edition`·`-streaming`·`-resilience`·`-diagnostics` +> → `grpc-advanced`로 합쳐졌다. `grpc-advanced-compat`은 그대로다. 패키지 이름은 바뀌지 않았다. 현재 +> leaf 목록은 registry(`src/config/architecture/modules.json`)가 SSOT다. + ### Stable — `src/grpc/` | leaf | 원본 모듈 | 담는 Task | 의존 | diff --git a/docs/runbooks/grpc-advanced-capabilities.md b/docs/runbooks/grpc-advanced-capabilities.md index b215663..bc3a50d 100644 --- a/docs/runbooks/grpc-advanced-capabilities.md +++ b/docs/runbooks/grpc-advanced-capabilities.md @@ -3,7 +3,7 @@ Scope: the `:grpc-advanced:*` family. Everything here is off by default and stays off until a deployment names it. Nothing in this family ships in a runtime composition today. -Flags are `ca-skeleton.grpc.advanced..enabled`. `GrpcAdvancedCapability` owns the list of +Flags are `app.grpc.advanced..enabled`. `GrpcAdvancedCapability` owns the list of capability names; `GrpcAdvancedSupportMatrix` owns their current grades. --- @@ -38,9 +38,9 @@ bound. 3. `NO_SNAPSHOT_YET` on a starting instance means it never reached the control plane. It fails after the initial fetch timeout rather than starting with no routing. -**Do not** add application-level retry policy while xDS is enabled. `GrpcXdsStartupGuard` refuses it, -because retry defined in two places has a winner that depends on resolution order rather than on a -decision. +**Do not** add application-level retry policy while xDS is enabled. `GrpcXdsProfile` refuses an +`APPLICATION` retry owner, because retry defined in two places has a winner that depends on +resolution order rather than on a decision. --- @@ -52,17 +52,15 @@ the proxy did not expose. Check that the proxy's CORS `expose_headers` includes configuration in `envoy/envoy.yaml` shows it in place. **If the method is client- or bidirectional-streaming**, it cannot work over gRPC-Web at all — a -browser has no way to send a stream of messages. `GrpcWebCompatibilityGate` reports such a method -before it is exposed. +browser has no way to send a stream of messages. `GrpcWebRpcSupport.require` refuses such a method. --- ## Servlet: a transport setting appears to be ignored It is ignored. The container owns the socket, so keepalive tuning, maximum connection age and -flow-control window tuning belong to it. `GrpcServletStartupValidator` refuses those settings at -startup rather than accepting and dropping them, because a setting that is silently ignored sends the -investigation somewhere else. +flow-control window tuning belong to it. This repository has no Servlet transport code that would +refuse them, so configure them on the container. A Servlet run never substitutes for Netty certification. @@ -86,13 +84,11 @@ rather than retrying a failure. ## Promoting a capability -`GrpcAdvancedPromotionGate.evaluate` names every missing item. Promotion to `ADVANCED_STABLE` needs -compatibility evidence, a security review, fault evidence, performance evidence, an ADR, a runbook, a -real-environment test and seven days of soak. A Stable default needs thirty. +Promotion to `ADVANCED_STABLE` needs compatibility evidence, a security review, fault evidence, +performance evidence, an ADR, a runbook, a real-environment test and seven days of soak. A Stable +default needs thirty. Promotions are independent: promoting one capability changes no other's +grade. This is a review checklist; the in-code `GrpcAdvancedPromotionGate` that restated it was +removed (review 2026-09-24 S5-lead-4) because nothing but its own test called it. -Promotions are independent: promoting one capability changes no other's grade, and -`GrpcAdvancedSupportMatrix.apply` refuses a decision made against a different matrix state. - -Before citing a suite as evidence, check `GrpcAdvancedInfrastructureTestkit.missingInfrastructure`. -A suite that ran without the proxy, the container, the control plane or the toolchain it needs passed -and established nothing. +Before citing a suite as evidence, check that it ran against the real infrastructure it needs (proxy, +container, control plane or toolchain). A suite that ran without it passed and established nothing. diff --git a/docs/runbooks/grpc-platform-operations.md b/docs/runbooks/grpc-platform-operations.md index 9ce0587..07d0639 100644 --- a/docs/runbooks/grpc-platform-operations.md +++ b/docs/runbooks/grpc-platform-operations.md @@ -5,8 +5,8 @@ empty — so nothing here fires in production yet. It is written now because the the ones an on-call cannot work out from first principles at three in the morning, and shipping the behaviour before the runbook means the first person to meet one is doing that. -Configuration lives under `ca-skeleton.grpc.platform.*` and is bound by `GrpcPlatformProperties`. -The platform does not start unless `ca-skeleton.grpc.platform.enabled=true`. +Configuration lives under `app.grpc.platform.*` and is bound by `GrpcPlatformProperties`. +The platform does not start unless `app.grpc.platform.enabled=true`. --- @@ -94,7 +94,7 @@ capacity on nothing. means the bottleneck is admission, not the work. 2. Check which saturation counter is moving — executor, channel or flow control. They look identical in a latency graph and have different fixes. -3. Raising `ca-skeleton.grpc.platform.executor-queue-capacity` defers the problem; it does not remove +3. Raising `app.grpc.platform.executor-queue-capacity` defers the problem; it does not remove it. `GrpcExecutorProfile` refuses a queue above ten thousand for that reason. --- @@ -138,5 +138,5 @@ construction rather than redacted. - **Reflection in production.** `GrpcReflectionMode.defaultFor` returns `DISABLED` for `STAGE` and `PROD`. Reflection publishes the whole schema to anyone who can open a connection. - **Every advanced capability.** See `docs/runbooks/grpc-advanced-capabilities.md`. -- **The platform itself.** `ca-skeleton.grpc.platform.enabled` defaults to false, and every `:grpc:*` +- **The platform itself.** `app.grpc.platform.enabled` defaults to false, and every `:grpc:*` leaf is build-only in the registry. diff --git a/grpc-advanced/CLAUDE.md b/grpc-advanced/CLAUDE.md index 9d60b56..3955a52 100644 --- a/grpc-advanced/CLAUDE.md +++ b/grpc-advanced/CLAUDE.md @@ -16,8 +16,7 @@ grpc:* → grpc-advanced:* (금지 — registry가 거부한다) ``` `grpc-spring-boot-starter`의 registry 엔트리에는 어떤 advanced id도 없다. -`verifyCleanArchitectureDependencies`가 build time에, `GrpcStableBuildInvariant`와 -`GrpcAdvancedModuleGuard.requireStableStarterIsClean`이 runtime에 같은 규칙을 강제한다. +`verifyCleanArchitectureDependencies`가 build time에 이 규칙을 강제한다. runtime 검사는 없다. ## Capability grade와 feature flag @@ -32,46 +31,52 @@ capability마다 별도 flag를 갖는다. 하나의 "advanced" 스위치로 묶 | `WATCH` | X (추적만) | — | | `DISABLED` | X | — | -property key는 `ca-skeleton.grpc.advanced..enabled`이고 전부 기본 off다. +property key는 `app.grpc.advanced..enabled`이고 전부 기본 off다. `GrpcAdvancedModuleGuard`가 세 조건(flag 미설정 / grade가 시작 불가 / production 승인 없음)을 구분해서 거부하며, 세 경우의 조치가 다르므로 메시지도 다르다. ## Leaf별 담당 capability -| leaf | 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` | read-only hedging, custom name resolver SPI, custom load balancer SPI, proxyless xDS | -| `grpc-advanced-compat` | gRPC-Web, Servlet HTTP/2, Spring Integration bridge, Reactor adapter, Kotlin 경계 | -| `grpc-advanced-diagnostics` | Channelz/CSDS 진단, advanced infrastructure testkit 요구사항 | +| 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별로 독립이다 -`GrpcAdvancedPromotionEvidence`는 capability마다 별도 레코드다. 공유 레코드였다면 하나를 승격할 때 -같은 시점에 측정된 다른 것들이 함께 승격된다. `GrpcAdvancedPromotionGate.capabilitiesDraggedAlong`이 -항상 빈 리스트인 것은 주석이 아니라 테스트되는 속성이다. +승격 증거는 capability마다 따로 판단한다. 공유 증거였다면 하나를 승격할 때 같은 시점에 측정된 다른 +것들이 함께 승격된다. 이 규칙을 코드로 옮겨 두었던 `GrpcAdvancedPromotionGate`는 자기 테스트 말고 +호출처가 없어 삭제했다(리뷰 2026-09-24 S5-lead-4). 지금은 `docs/runbooks/grpc-advanced-capabilities.md`의 +리뷰 규칙이다. 승격 문턱은 두 개다: `ADVANCED_STABLE`은 7일 soak + 전체 증거, Stable default는 30일 soak. 두 번째가 더 높은 이유는 모든 배포가 그 의존성과 장애 모드를 갖게 되기 때문이다. ## 이 저장소에서 검증할 수 없는 것 -`GrpcAdvancedInfrastructureTestkit`이 capability별로 필요한 실제 인프라를 명시한다. +capability별로 필요한 실제 인프라가 이 저장소에 없다. - `grpc-web` → gRPC-Web 프록시 - `servlet-compat` → Servlet 컨테이너 - `xds` → 중지 가능한 xDS control plane -- `kotlin` → Kotlin 툴체인 (**이 저장소에 없다**) +- `kotlin` → Kotlin 툴체인 인프라 없이 도는 suite는 통과하면서 아무것도 증명하지 않으므로, suite가 없는 것보다 나쁘다. -`GrpcKotlinCompatibilityGate.supportableHere()`가 `false`를 반환하는 것은 그 사실의 코드 표현이다 — -Kotlin 계약 요구사항 4개는 검증되지만 compile lane은 존재하지 않는다. +이 사실을 상수로 반환하던 gate 클래스(`GrpcKotlinCompatibilityGate`, `GrpcAdvancedInfrastructureTestkit` +등)는 2026-09-25 삭제됐다 — 지원 여부는 이 문서와 support matrix가 적는다. ## 금지 - Stable leaf(`grpc:*`)가 이 family를 참조하는 것. - capability grade 없이, 또는 flag 없이 advanced 코드 경로를 실행하는 것. -- `WATCH` capability를 스키마 소스로 사용하는 것 (`GrpcEdition2026Guard`가 무조건 거부한다). +- `WATCH` capability를 스키마 소스로 사용하는 것. - 실제 인프라 없이 실행한 suite를 promotion evidence로 인용하는 것. diff --git a/grpc-advanced/grpc-advanced-bootstrap/build.gradle b/grpc-advanced/grpc-advanced-bootstrap/build.gradle deleted file mode 100644 index 347ed7d..0000000 --- a/grpc-advanced/grpc-advanced-bootstrap/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// The Advanced boundary itself: capability grades, the `ca-skeleton.grpc.advanced.*` feature-flag -// contract, the module guard that refuses an unflagged capability, and the per-capability -// promotion gate. -// -// This leaf depends on Stable public types and never the other way round. The Stable starter's -// registry entry names no advanced id, so `verifyCleanArchitectureDependencies` is what makes -// "Advanced never leaks into Stable" a build failure rather than a review note. -dependencies { - api project(':grpc:grpc-core-api') -} diff --git a/grpc-advanced/grpc-advanced-bootstrap/gradle.lockfile b/grpc-advanced/grpc-advanced-bootstrap/gradle.lockfile deleted file mode 100644 index e2c9585..0000000 --- a/grpc-advanced/grpc-advanced-bootstrap/gradle.lockfile +++ /dev/null @@ -1,84 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.21.0=spotbugs -info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle -org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle -org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle -org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath -org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle -org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle -org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle -org.codehaus.plexus:plexus-utils:3.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit:junit-bom:6.1.0=spotbugs -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath -org.ow2.asm:asm-analysis:9.10.1=spotbugs -org.ow2.asm:asm-commons:9.10.1=spotbugs -org.ow2.asm:asm-tree:9.10.1=spotbugs -org.ow2.asm:asm-util:9.10.1=spotbugs -org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionDecision.java b/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionDecision.java deleted file mode 100644 index 9d4ef31..0000000 --- a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionDecision.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.grpc.advanced.release; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcCapabilityGrade; -import java.util.List; - -/** - * Whether one capability moves to a new grade. - * - *

Carries the grade it would move to as well as the blockers, so a refusal says what was being - * asked for. "Not promoted" is ambiguous between a failed promotion to Advanced Stable and a failed - * promotion to a Stable default, and the second is a much larger decision. - */ -public record GrpcAdvancedPromotionDecision( - GrpcAdvancedCapability capability, - GrpcCapabilityGrade from, - GrpcCapabilityGrade to, - boolean promoted, - List blockers) { - - /** Requires blockers exactly when refused. */ - public GrpcAdvancedPromotionDecision { - if (capability == null || from == null || to == null || blockers == null) { - throw new IllegalArgumentException( - "a promotion decision names its capability and both grades"); - } - blockers = List.copyOf(blockers); - if (promoted && !blockers.isEmpty()) { - throw new IllegalArgumentException("a granted promotion has no blockers"); - } - if (!promoted && blockers.isEmpty()) { - throw new IllegalArgumentException("a refused promotion says why"); - } - } - - /** A granted promotion. */ - public static GrpcAdvancedPromotionDecision grant( - GrpcAdvancedCapability capability, GrpcCapabilityGrade from, GrpcCapabilityGrade to) { - return new GrpcAdvancedPromotionDecision(capability, from, to, true, List.of()); - } - - /** A refused promotion. */ - public static GrpcAdvancedPromotionDecision refuse( - GrpcAdvancedCapability capability, - GrpcCapabilityGrade from, - GrpcCapabilityGrade to, - List blockers) { - return new GrpcAdvancedPromotionDecision(capability, from, to, false, blockers); - } -} diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionEvidence.java b/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionEvidence.java deleted file mode 100644 index f5a81c2..0000000 --- a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionEvidence.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.grpc.advanced.release; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import java.time.Duration; -import java.util.Set; - -/** - * What one capability has behind it. - * - *

Per capability, never shared. The Stable plan's requirement that Edition, streaming, xDS, - * gRPC-Web, Servlet and the language adapters do not gate each other only means something if their - * evidence is separate: a shared record makes promoting one of them promote whichever others - * happened to be measured at the same time. - */ -public record GrpcAdvancedPromotionEvidence( - GrpcAdvancedCapability capability, - boolean compatibilityEvidence, - boolean securityReview, - boolean faultEvidence, - boolean performanceEvidence, - Duration soakDuration, - boolean architectureDecisionRecord, - boolean runbook, - boolean realEnvironmentTest) { - - /** Requires a capability and a non-negative soak. */ - public GrpcAdvancedPromotionEvidence { - if (capability == null) { - throw new IllegalArgumentException("promotion evidence names its capability"); - } - if (soakDuration == null || soakDuration.isNegative()) { - throw new IllegalArgumentException("a soak duration must be present and non-negative"); - } - } - - /** No evidence at all, which is where a capability starts. */ - public static GrpcAdvancedPromotionEvidence none(GrpcAdvancedCapability capability) { - return new GrpcAdvancedPromotionEvidence( - capability, false, false, false, false, Duration.ZERO, false, false, false); - } - - /** Everything a promotion to Advanced Stable needs. */ - public static GrpcAdvancedPromotionEvidence complete( - GrpcAdvancedCapability capability, Duration soakDuration) { - return new GrpcAdvancedPromotionEvidence( - capability, true, true, true, true, soakDuration, true, true, true); - } - - /** Which required items are absent, as a set a report can print. */ - public Set missing() { - Set missing = new java.util.LinkedHashSet<>(); - if (!compatibilityEvidence) { - missing.add("compatibility evidence"); - } - if (!securityReview) { - missing.add("security review"); - } - if (!faultEvidence) { - missing.add("fault evidence"); - } - if (!performanceEvidence) { - missing.add("performance evidence"); - } - if (!architectureDecisionRecord) { - missing.add("architecture decision record"); - } - if (!runbook) { - missing.add("runbook"); - } - if (!realEnvironmentTest) { - missing.add("real environment test"); - } - return Set.copyOf(missing); - } -} diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionGate.java b/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionGate.java deleted file mode 100644 index 3947536..0000000 --- a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionGate.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.grpc.advanced.release; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcCapabilityGrade; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; - -/** - * Decides one capability's promotion, on its own evidence. - * - *

Two thresholds rather than one. Reaching Advanced Stable means the capability works and is - * documented; becoming a Stable default means every deployment gets it, which additionally puts its - * dependencies on every classpath and its failure modes in every on-call rotation. The second needs - * the first plus a longer soak, because a capability that has run in one deployment for a week is - * not the same claim as one that ships to all of them. - */ -public final class GrpcAdvancedPromotionGate { - - /** The soak a promotion to Advanced Stable requires. */ - public static final Duration ADVANCED_STABLE_SOAK = Duration.ofDays(7); - - /** The soak a promotion to a Stable default requires. */ - public static final Duration STABLE_DEFAULT_SOAK = Duration.ofDays(30); - - private GrpcAdvancedPromotionGate() {} - - /** - * Whether {@code capability} may move from {@code from} to {@code to}. - * - * @throws IllegalArgumentException when the transition is not one this gate governs - */ - public static GrpcAdvancedPromotionDecision evaluate( - GrpcAdvancedPromotionEvidence evidence, GrpcCapabilityGrade from, GrpcCapabilityGrade to) { - if (evidence == null || from == null || to == null) { - throw new IllegalArgumentException("a promotion needs evidence and both grades"); - } - if (from == to) { - throw new IllegalArgumentException("a promotion changes the grade"); - } - GrpcAdvancedCapability capability = evidence.capability(); - List blockers = new ArrayList<>(); - - evidence.missing().stream() - .sorted() - .forEach(missing -> blockers.add(capability.flagName() + " has no " + missing)); - - Duration requiredSoak = - to == GrpcCapabilityGrade.ADVANCED_STABLE ? ADVANCED_STABLE_SOAK : STABLE_DEFAULT_SOAK; - if (evidence.soakDuration().compareTo(requiredSoak) < 0) { - blockers.add( - capability.flagName() - + " soaked for " - + evidence.soakDuration().toDays() - + " day(s); promotion to " - + to - + " requires " - + requiredSoak.toDays()); - } - if (from == GrpcCapabilityGrade.WATCH && to != GrpcCapabilityGrade.EXPERIMENTAL) { - blockers.add( - capability.flagName() - + " is WATCH, which is tracked rather than implemented; it becomes EXPERIMENTAL " - + "before anything else"); - } - return blockers.isEmpty() - ? GrpcAdvancedPromotionDecision.grant(capability, from, to) - : GrpcAdvancedPromotionDecision.refuse(capability, from, to, blockers); - } - - /** - * Whether promoting {@code promoted} would drag another capability with it. - * - *

Always empty, and the method exists so a test can assert that rather than a comment claiming - * it: each capability's evidence is its own record, so there is no path by which one promotion - * changes another's grade. - */ - public static List capabilitiesDraggedAlong( - GrpcAdvancedCapability promoted) { - if (promoted == null) { - throw new IllegalArgumentException("a capability is required"); - } - return List.of(); - } -} diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedSupportMatrix.java b/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedSupportMatrix.java deleted file mode 100644 index 568e3ed..0000000 --- a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedSupportMatrix.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.grpc.advanced.release; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcCapabilityGrade; -import java.util.EnumMap; -import java.util.Map; - -/** - * Every advanced capability's current grade, in one place an adopter can read. - * - *

The published answer to "is this supported". Without it the answer is inferred from whether a - * class exists, which says only that somebody wrote it. - */ -public final class GrpcAdvancedSupportMatrix { - - private final Map grades = - new EnumMap<>(GrpcAdvancedCapability.class); - - /** A matrix at each capability's default grade. */ - public GrpcAdvancedSupportMatrix() { - for (GrpcAdvancedCapability capability : GrpcAdvancedCapability.values()) { - grades.put(capability, capability.defaultGrade()); - } - } - - /** The grade of one capability. */ - public GrpcCapabilityGrade gradeOf(GrpcAdvancedCapability capability) { - if (capability == null) { - throw new IllegalArgumentException("a capability is required"); - } - return grades.get(capability); - } - - /** - * Applies a granted promotion. - * - * @throws IllegalArgumentException when the decision's starting grade is not the current one, - * which means two promotions raced or one was replayed - */ - public GrpcAdvancedSupportMatrix apply(GrpcAdvancedPromotionDecision decision) { - if (decision == null) { - throw new IllegalArgumentException("a decision is required"); - } - if (!decision.promoted()) { - return this; - } - GrpcCapabilityGrade current = grades.get(decision.capability()); - if (current != decision.from()) { - throw new IllegalArgumentException( - "capability '" - + decision.capability().flagName() - + "' is " - + current - + ", not " - + decision.from() - + "; this decision was made against a different matrix"); - } - grades.put(decision.capability(), decision.to()); - return this; - } - - /** The whole matrix. */ - public Map snapshot() { - return Map.copyOf(grades); - } -} diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionGateTest.java b/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionGateTest.java deleted file mode 100644 index ec80715..0000000 --- a/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/release/GrpcAdvancedPromotionGateTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package dev.caskeleton.grpc.advanced.release; - -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.GrpcCapabilityGrade; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcAdvancedPromotionGateTest { - - @Test - @DisplayName("a capability with complete evidence and a full soak is promoted") - void completeEvidencePromotes() { - GrpcAdvancedPromotionDecision decision = - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.complete( - GrpcAdvancedCapability.HEDGING, Duration.ofDays(7)), - GrpcCapabilityGrade.EXPERIMENTAL, - GrpcCapabilityGrade.ADVANCED_STABLE); - - assertThat(decision.promoted()).isTrue(); - assertThat(decision.blockers()).isEmpty(); - } - - @Test - @DisplayName("every missing piece of evidence is named") - void everyMissingPieceIsNamed() { - GrpcAdvancedPromotionDecision decision = - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.none(GrpcAdvancedCapability.XDS), - GrpcCapabilityGrade.EXPERIMENTAL, - GrpcCapabilityGrade.ADVANCED_STABLE); - - assertThat(decision.blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("compatibility evidence")) - .anySatisfy(blocker -> assertThat(blocker).contains("security review")) - .anySatisfy(blocker -> assertThat(blocker).contains("fault evidence")) - .anySatisfy(blocker -> assertThat(blocker).contains("runbook")) - .anySatisfy(blocker -> assertThat(blocker).contains("real environment test")) - .anySatisfy(blocker -> assertThat(blocker).contains("soaked for")); - } - - @Test - @DisplayName("becoming a Stable default needs a longer soak than becoming Advanced Stable") - void theStableDefaultThresholdIsHigher() { - GrpcAdvancedPromotionEvidence weekLongSoak = - GrpcAdvancedPromotionEvidence.complete(GrpcAdvancedCapability.GRPC_WEB, Duration.ofDays(7)); - - assertThat( - GrpcAdvancedPromotionGate.evaluate( - weekLongSoak, - GrpcCapabilityGrade.EXPERIMENTAL, - GrpcCapabilityGrade.ADVANCED_STABLE) - .promoted()) - .isTrue(); - assertThat( - GrpcAdvancedPromotionGate.evaluate( - weekLongSoak, GrpcCapabilityGrade.ADVANCED_STABLE, GrpcCapabilityGrade.DISABLED) - .blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("requires 30")); - } - - @Test - @DisplayName("a WATCH capability becomes EXPERIMENTAL before anything else") - void watchPromotesOnlyToExperimental() { - assertThat( - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.complete( - GrpcAdvancedCapability.EDITION_2026, Duration.ofDays(60)), - GrpcCapabilityGrade.WATCH, - GrpcCapabilityGrade.ADVANCED_STABLE) - .blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("becomes EXPERIMENTAL")); - assertThat( - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.complete( - GrpcAdvancedCapability.EDITION_2026, Duration.ofDays(60)), - GrpcCapabilityGrade.WATCH, - GrpcCapabilityGrade.EXPERIMENTAL) - .promoted()) - .isTrue(); - } - - @Test - @DisplayName("promoting one capability drags none of the others with it") - void promotionsAreIndependent() { - GrpcAdvancedSupportMatrix matrix = new GrpcAdvancedSupportMatrix(); - GrpcCapabilityGrade webBefore = matrix.gradeOf(GrpcAdvancedCapability.GRPC_WEB); - - matrix.apply( - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.complete( - GrpcAdvancedCapability.HEDGING, Duration.ofDays(7)), - GrpcCapabilityGrade.EXPERIMENTAL, - GrpcCapabilityGrade.ADVANCED_STABLE)); - - assertThat(matrix.gradeOf(GrpcAdvancedCapability.HEDGING)) - .isEqualTo(GrpcCapabilityGrade.ADVANCED_STABLE); - assertThat(matrix.gradeOf(GrpcAdvancedCapability.GRPC_WEB)).isEqualTo(webBefore); - assertThat(GrpcAdvancedPromotionGate.capabilitiesDraggedAlong(GrpcAdvancedCapability.HEDGING)) - .isEmpty(); - } - - @Test - @DisplayName("a decision made against a different matrix state is refused") - void aStaleDecisionIsRefused() { - GrpcAdvancedSupportMatrix matrix = new GrpcAdvancedSupportMatrix(); - - assertThatThrownBy( - () -> - matrix.apply( - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.complete( - GrpcAdvancedCapability.GRPC_WEB, Duration.ofDays(7)), - GrpcCapabilityGrade.EXPERIMENTAL, - GrpcCapabilityGrade.ADVANCED_STABLE))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("made against a different matrix"); - } - - @Test - @DisplayName("a refused promotion leaves the matrix alone") - void aRefusedPromotionChangesNothing() { - GrpcAdvancedSupportMatrix matrix = new GrpcAdvancedSupportMatrix(); - - matrix.apply( - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.none(GrpcAdvancedCapability.XDS), - GrpcCapabilityGrade.EXPERIMENTAL, - GrpcCapabilityGrade.ADVANCED_STABLE)); - - assertThat(matrix.gradeOf(GrpcAdvancedCapability.XDS)) - .isEqualTo(GrpcCapabilityGrade.EXPERIMENTAL); - } - - @Test - @DisplayName("a promotion that changes nothing is refused") - void aNoOpPromotionIsRefused() { - assertThatThrownBy( - () -> - GrpcAdvancedPromotionGate.evaluate( - GrpcAdvancedPromotionEvidence.none(GrpcAdvancedCapability.XDS), - GrpcCapabilityGrade.EXPERIMENTAL, - GrpcCapabilityGrade.EXPERIMENTAL)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/grpc-advanced/grpc-advanced-compat/build.gradle b/grpc-advanced/grpc-advanced-compat/build.gradle index 011791e..bf0fccd 100644 --- a/grpc-advanced/grpc-advanced-compat/build.gradle +++ b/grpc-advanced/grpc-advanced-compat/build.gradle @@ -1,21 +1,20 @@ plugins { - id 'ca.platform-module' + // 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 Servlet HTTP/2 profile, the Spring Integration bridge, the -// Reactor adapter, and the Kotlin coroutine/Flow boundary. +// 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 lane -// is expressed as a Java-side boundary contract whose compatibility gate fails closed until a real -// toolchain lane exists. Everything the gate would otherwise assert — one schema source, coroutine -// cancellation propagation, Flow backpressure inside the Stable buffer limits, evidence type -// preservation — is a checkable contract without it. +// 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-policy') - api project(':grpc:grpc-server') - api project(':grpc:grpc-client') - api project(':grpc-advanced:grpc-advanced-bootstrap') + 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 diff --git a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinCompatibilityGate.java b/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinCompatibilityGate.java deleted file mode 100644 index 46d3e63..0000000 --- a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinCompatibilityGate.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.grpc.advanced.kotlin; - -import java.util.ArrayList; -import java.util.List; - -/** - * Whether a Kotlin adapter may be advertised as supported. - * - *

Fails closed in this repository, and says so rather than reporting a pass it cannot justify. - * There is no Kotlin toolchain here (adaptation design D7), so the compile lane that would - * establish the last requirement has never run; a gate that reported success anyway would put an - * unverified claim in the support matrix. - * - *

The other four requirements are checkable and are checked, so turning the toolchain on later - * is a lane to add rather than a contract to write. - */ -public final class GrpcKotlinCompatibilityGate { - - private GrpcKotlinCompatibilityGate() {} - - /** - * Every reason a Kotlin adapter is not yet supportable. - * - * @param toolchainLaneRan whether a Kotlin compile lane actually ran against this profile - * @return an empty list only when the profile is complete and its lane has run - */ - public static List blockers(GrpcKotlinProfile profile, boolean toolchainLaneRan) { - if (profile == null) { - throw new IllegalArgumentException("a Kotlin profile is required"); - } - List blockers = new ArrayList<>(); - if (!profile.sharesSchemaSourceWithJava()) { - blockers.add( - "the Kotlin contract does not share one schema source with the Java contract; two " - + "sources diverge where only somebody reading both would notice"); - } - if (!profile.propagatesCoroutineCancellation()) { - blockers.add( - "coroutine cancellation does not reach the gRPC call; a cancelled scope would leave the " - + "call running"); - } - if (!profile.respectsStableFlowControl()) { - blockers.add( - "Flow backpressure bypasses the Stable buffer bounds; a slow collector would buffer " - + "without a limit rather than terminating the stream"); - } - if (!profile.preservesPlatformEvidenceTypes()) { - blockers.add( - "the adapter does not preserve the platform's evidence, status and deadline types; a " - + "Kotlin-idiomatic re-creation is a second model of the same facts"); - } - if (!toolchainLaneRan) { - blockers.add( - "no Kotlin toolchain lane has run against " - + profile.kotlinToolchainVersion() - + "; this repository has no Kotlin toolchain, so the compile evidence does not exist"); - } - return List.copyOf(blockers); - } - - /** - * Whether the Kotlin adapter is supportable in this repository as it stands. - * - *

False. The four contract requirements can be satisfied; the toolchain lane cannot. - */ - public static boolean supportableHere() { - return false; - } -} diff --git a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinProfile.java b/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinProfile.java deleted file mode 100644 index fb2b83f..0000000 --- a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinProfile.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.grpc.advanced.kotlin; - -/** - * How a Kotlin adapter must behave, stated from the Java side. - * - *

Java-side because this repository has no Kotlin toolchain (adaptation design D7). What can be - * expressed without one is every rule that constrains the adapter: one schema source shared with - * the Java contract, coroutine cancellation propagated to the call, Flow backpressure inside the - * Stable buffer bounds, and the platform's evidence and status types preserved rather than - * re-created in Kotlin idiom. - * - *

Each is a component so the gate can check them individually. A single "compatible" flag would - * let a partially compliant adapter through, and the most likely partial failure — a Flow that - * buffers without a bound — is the one with the worst production behaviour. - */ -public record GrpcKotlinProfile( - boolean sharesSchemaSourceWithJava, - boolean propagatesCoroutineCancellation, - boolean respectsStableFlowControl, - boolean preservesPlatformEvidenceTypes, - String kotlinToolchainVersion) { - - /** Refuses a profile that claims support without naming a toolchain. */ - public GrpcKotlinProfile { - if (kotlinToolchainVersion == null || kotlinToolchainVersion.isBlank()) { - throw new IllegalArgumentException( - "a Kotlin profile names the toolchain it was verified against; 'Kotlin' is not a version"); - } - } - - /** A profile for a toolchain this repository has not verified. */ - public static GrpcKotlinProfile unverified(String kotlinToolchainVersion) { - return new GrpcKotlinProfile(false, false, false, false, kotlinToolchainVersion); - } -} diff --git a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCapabilityMatrix.java b/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCapabilityMatrix.java deleted file mode 100644 index da912e8..0000000 --- a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCapabilityMatrix.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.grpc.advanced.servlet; - -import java.util.Set; - -/** - * What a Servlet container can and cannot do compared with Netty. - * - *

The gaps are not incidental. A Servlet container owns the socket, so everything below the - * request abstraction belongs to it: keepalive, connection age, and the flow-control window are the - * container's settings, not gRPC's. Naming them is what stops a deployment from configuring a - * keepalive that is silently ignored and concluding the client is at fault. - */ -public enum GrpcServletCapabilityMatrix { - /** HTTP/2 request and response. Available. */ - HTTP2(true), - /** TLS. Available, terminated by the container. */ - TLS(true), - /** Inbound message and metadata limits. Available. */ - MESSAGE_LIMITS(true), - /** The standard health service. Available. */ - HEALTH(true), - /** Server reflection. Available. */ - REFLECTION(true), - /** Graceful shutdown. Available through the container's lifecycle. */ - GRACEFUL_SHUTDOWN(true), - /** gRPC-level keepalive tuning. The container owns the connection. */ - KEEPALIVE_TUNING(false), - /** Maximum connection age. The container owns the connection. */ - MAX_CONNECTION_AGE(false), - /** HTTP/2 flow-control window tuning. The container owns the transport. */ - FLOW_CONTROL_WINDOW_TUNING(false); - - private final boolean available; - - GrpcServletCapabilityMatrix(boolean available) { - this.available = available; - } - - /** Whether the Servlet transport provides this. */ - public boolean available() { - return available; - } - - /** Everything the Servlet transport cannot do. */ - public static Set unavailable() { - return java.util.Arrays.stream(values()) - .filter(capability -> !capability.available()) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - } -} diff --git a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCompatibilityProfile.java b/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCompatibilityProfile.java deleted file mode 100644 index 8363b0d..0000000 --- a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCompatibilityProfile.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.grpc.advanced.servlet; - -import dev.caskeleton.grpc.server.GrpcServerTransport; - -/** - * A deployment that serves gRPC from its Servlet container, on the web server's own port. - * - *

Attractive because it is one port, one TLS configuration and one lifecycle. The cost is that - * the container owns the transport, so the Netty settings a Stable profile carries have no effect — - * and this profile refuses to pretend otherwise. - * - *

Its evidence never counts as Netty certification. A suite that passes here has established - * that the container serves gRPC, not that the platform's Netty profile is correct. - */ -public record GrpcServletCompatibilityProfile( - String contextPath, boolean containerOwnsTls, boolean asyncSupported) { - - /** Refuses a configuration the container cannot honour. */ - public GrpcServletCompatibilityProfile { - if (contextPath == null || !contextPath.startsWith("/")) { - throw new IllegalArgumentException( - "a servlet profile needs a context path starting with '/'"); - } - if (!asyncSupported) { - throw new IllegalArgumentException( - "gRPC over Servlet requires async support; without it every streaming call blocks a " - + "container thread for its lifetime"); - } - if (!containerOwnsTls) { - throw new IllegalArgumentException( - "the container owns the socket, so it owns TLS; a profile that claims otherwise " - + "configures a setting nothing reads"); - } - } - - /** The transport this profile runs on. */ - public GrpcServerTransport transport() { - return GrpcServerTransport.SERVLET; - } - - /** - * Whether a run under this profile certifies the platform's Netty transport. - * - *

Always false. The container's HTTP/2 is real, but it is the container's: its keepalive, its - * connection age and its flow-control window. Stable certification is a statement about the - * platform's own Netty profile, and a Servlet run establishes nothing about it. - */ - public boolean certifiesNettyTransport() { - return false; - } -} diff --git a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletStartupValidator.java b/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletStartupValidator.java deleted file mode 100644 index 8df49a9..0000000 --- a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletStartupValidator.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.grpc.advanced.servlet; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * Refuses a Servlet deployment that asks for something the container will not do. - * - *

Refuses rather than warns, because the setting would otherwise be accepted and ignored. A - * keepalive configured on a Servlet deployment does nothing, the connections behave as the - * container decides, and the investigation starts from the assumption that the setting is in force. - */ -public final class GrpcServletStartupValidator { - - private GrpcServletStartupValidator() {} - - /** - * Every requested capability the Servlet transport cannot provide. - * - * @param requestedCapabilities the transport settings the deployment configured - * @return an empty list when everything requested is available - */ - public static List violations( - GrpcServletCompatibilityProfile profile, - Set requestedCapabilities) { - if (profile == null || requestedCapabilities == null) { - throw new IllegalArgumentException("validation needs the profile and the requested set"); - } - List violations = new ArrayList<>(); - requestedCapabilities.stream() - .filter(capability -> !capability.available()) - .sorted() - .forEach( - capability -> - violations.add( - capability - + " is not available on the Servlet transport; the container owns the " - + "connection, so this setting would be accepted and ignored")); - return List.copyOf(violations); - } - - /** - * Whether a Servlet run may stand in for Netty certification. - * - *

Always false. - */ - public static boolean substitutesForNettyCertification() { - return false; - } -} diff --git a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebCompatibilityGate.java b/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebCompatibilityGate.java deleted file mode 100644 index 2ad2677..0000000 --- a/grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebCompatibilityGate.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.grpc.advanced.web; - -import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.RpcType; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Checks that everything exposed to browsers can actually be served to them, on the same schema as - * the native clients. - * - *

The same schema is the point. Two schemas — one for browsers, one for services — is how a - * field ends up meaning something different depending on which client asked, and the divergence is - * only visible to whoever reads both files. - */ -public final class GrpcWebCompatibilityGate { - - private GrpcWebCompatibilityGate() {} - - /** - * Every method this profile could not serve. - * - * @param exposedMethods the methods a browser is meant to be able to call - * @return an empty list when every exposed method is servable - */ - public static List violations(Map exposedMethods) { - if (exposedMethods == null) { - throw new IllegalArgumentException("an exposed method map is required"); - } - List violations = new ArrayList<>(); - exposedMethods.entrySet().stream() - .sorted(java.util.Comparator.comparing(entry -> entry.getKey().canonical())) - .forEach( - entry -> { - if (!GrpcWebRpcSupport.supported(entry.getValue())) { - violations.add( - "method '" - + entry.getKey().canonical() - + "' is " - + entry.getValue() - + ", which gRPC-Web cannot carry"); - } - }); - return List.copyOf(violations); - } - - /** - * Whether the browser and native suites must run against one schema. - * - *

Always true. Stated as a method so the property is asserted rather than described. - */ - public static boolean sharesOneSchemaWithNativeClients() { - return true; - } -} diff --git a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcKotlinCompatibilityGateTest.java b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcCoroutineContextBridgeTest.java similarity index 53% rename from grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcKotlinCompatibilityGateTest.java rename to grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcCoroutineContextBridgeTest.java index 281aa54..cb5b08d 100644 --- a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcKotlinCompatibilityGateTest.java +++ b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcCoroutineContextBridgeTest.java @@ -4,8 +4,6 @@ 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.advanced.kotlin.GrpcKotlinCompatibilityGate; -import dev.caskeleton.grpc.advanced.kotlin.GrpcKotlinProfile; import dev.caskeleton.grpc.api.deadline.GrpcCancellationToken; import dev.caskeleton.grpc.deadline.GrpcCancellationCoordinator; import dev.caskeleton.grpc.deadline.GrpcCancellationReason; @@ -14,41 +12,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -class GrpcKotlinCompatibilityGateTest { +class GrpcCoroutineContextBridgeTest { private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - @Test - @DisplayName("the Kotlin adapter fails closed here, and says which lane is missing") - void theGateFailsClosed() { - GrpcKotlinProfile complete = new GrpcKotlinProfile(true, true, true, true, "2.1.0"); - - assertThat(GrpcKotlinCompatibilityGate.blockers(complete, false)) - .singleElement() - .satisfies(blocker -> assertThat(blocker).contains("no Kotlin toolchain")); - assertThat(GrpcKotlinCompatibilityGate.blockers(complete, true)).isEmpty(); - assertThat(GrpcKotlinCompatibilityGate.supportableHere()).isFalse(); - } - - @Test - @DisplayName("each Kotlin contract requirement is checked on its own") - void eachRequirementIsCheckedSeparately() { - assertThat(GrpcKotlinCompatibilityGate.blockers(GrpcKotlinProfile.unverified("2.1.0"), true)) - .hasSize(4) - .anySatisfy(blocker -> assertThat(blocker).contains("one schema source")) - .anySatisfy(blocker -> assertThat(blocker).contains("cancelled scope")) - .anySatisfy(blocker -> assertThat(blocker).contains("buffer without a limit")) - .anySatisfy(blocker -> assertThat(blocker).contains("second model of the same facts")); - } - - @Test - @DisplayName("a profile that claims support without naming a toolchain is refused") - void aProfileNamesItsToolchain() { - assertThatThrownBy(() -> GrpcKotlinProfile.unverified(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not a version"); - } - @Test @DisplayName("coroutine cancellation reaches the platform, and the platform reaches the scope") void cancellationCrossesBothWays() { diff --git a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcIntegrationBridgePolicyTest.java b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcIntegrationBridgePolicyTest.java index 5474b67..b687080 100644 --- a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcIntegrationBridgePolicyTest.java +++ b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcIntegrationBridgePolicyTest.java @@ -27,7 +27,7 @@ class GrpcIntegrationBridgePolicyTest { private static final GrpcMetadataKey CORRELATION = GrpcMetadataKey.ascii("x-correlation-id"); private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static GrpcRequestContext requestContext() { return GrpcRequestContext.create( diff --git a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcReactorContextBridgeTest.java b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcReactorContextBridgeTest.java index fcc3059..ee4d99b 100644 --- a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcReactorContextBridgeTest.java +++ b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcReactorContextBridgeTest.java @@ -28,7 +28,7 @@ import reactor.util.context.Context; class GrpcReactorContextBridgeTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); private static GrpcContextSnapshot snapshot() { diff --git a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcServletStartupValidatorTest.java b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcServletStartupValidatorTest.java deleted file mode 100644 index 127e04b..0000000 --- a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcServletStartupValidatorTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.grpc.advanced.compat; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.servlet.GrpcServletCapabilityMatrix; -import dev.caskeleton.grpc.advanced.servlet.GrpcServletCompatibilityProfile; -import dev.caskeleton.grpc.advanced.servlet.GrpcServletStartupValidator; -import dev.caskeleton.grpc.server.GrpcServerTransport; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcServletStartupValidatorTest { - - private static final GrpcServletCompatibilityProfile PROFILE = - new GrpcServletCompatibilityProfile("/grpc", true, true); - - @Test - @DisplayName("the Servlet transport names what it cannot do") - void theMatrixNamesItsGaps() { - assertThat(GrpcServletCapabilityMatrix.unavailable()) - .containsExactlyInAnyOrder( - GrpcServletCapabilityMatrix.KEEPALIVE_TUNING, - GrpcServletCapabilityMatrix.MAX_CONNECTION_AGE, - GrpcServletCapabilityMatrix.FLOW_CONTROL_WINDOW_TUNING); - assertThat(GrpcServletCapabilityMatrix.HTTP2.available()).isTrue(); - assertThat(GrpcServletCapabilityMatrix.GRACEFUL_SHUTDOWN.available()).isTrue(); - } - - @Test - @DisplayName("a deployment asking for a Netty-only setting is refused, not warned") - void aNettyOnlySettingIsRefused() { - assertThat( - GrpcServletStartupValidator.violations( - PROFILE, Set.of(GrpcServletCapabilityMatrix.KEEPALIVE_TUNING))) - .singleElement() - .satisfies(violation -> assertThat(violation).contains("accepted and ignored")); - assertThat( - GrpcServletStartupValidator.violations( - PROFILE, - Set.of( - GrpcServletCapabilityMatrix.KEEPALIVE_TUNING, - GrpcServletCapabilityMatrix.MAX_CONNECTION_AGE))) - .hasSize(2); - } - - @Test - @DisplayName("an available capability passes") - void anAvailableCapabilityPasses() { - assertThat( - GrpcServletStartupValidator.violations( - PROFILE, - Set.of(GrpcServletCapabilityMatrix.HTTP2, GrpcServletCapabilityMatrix.TLS))) - .isEmpty(); - } - - @Test - @DisplayName("a Servlet run never substitutes for Netty certification") - void servletIsNotNettyCertification() { - assertThat(GrpcServletStartupValidator.substitutesForNettyCertification()).isFalse(); - assertThat(PROFILE.certifiesNettyTransport()).isFalse(); - assertThat(PROFILE.transport()).isEqualTo(GrpcServerTransport.SERVLET); - assertThat(GrpcServerTransport.SERVLET.certifiesNetworkBehaviour()).isFalse(); - } - - @Test - @DisplayName("a profile without async support or container-owned TLS is refused") - void anIncoherentProfileIsRefused() { - assertThatThrownBy(() -> new GrpcServletCompatibilityProfile("/grpc", true, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("blocks a container thread"); - assertThatThrownBy(() -> new GrpcServletCompatibilityProfile("/grpc", false, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("a setting nothing reads"); - assertThatThrownBy(() -> new GrpcServletCompatibilityProfile("grpc", true, true)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityGateTest.java b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityTest.java similarity index 72% rename from grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityGateTest.java rename to grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityTest.java index ff67a6d..a34f687 100644 --- a/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityGateTest.java +++ b/grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcWebCompatibilityTest.java @@ -3,27 +3,23 @@ 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.GrpcWebCompatibilityGate; 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.GrpcMethodName; 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.Map; 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 GrpcWebCompatibilityGateTest { - - private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); - private static final GrpcMethodName UPLOAD = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/UploadDocument"); +class GrpcWebCompatibilityTest { @Test @DisplayName("gRPC-Web carries unary and server streaming, and nothing else") @@ -37,18 +33,6 @@ class GrpcWebCompatibilityGateTest { .hasMessageContaining("no way to send a stream of messages"); } - @Test - @DisplayName("a client-streaming method exposed to browsers is reported") - void anUnservableMethodIsReported() { - assertThat( - GrpcWebCompatibilityGate.violations( - Map.of(GET, RpcType.UNARY, UPLOAD, RpcType.CLIENT_STREAMING))) - .singleElement() - .satisfies(violation -> assertThat(violation).contains("UploadDocument")); - assertThat(GrpcWebCompatibilityGate.violations(Map.of(GET, RpcType.UNARY))).isEmpty(); - assertThat(GrpcWebCompatibilityGate.sharesOneSchemaWithNativeClients()).isTrue(); - } - @Test @DisplayName("a wildcard origin is refused, and cookie credentials require CSRF protection") void browserCredentialRulesDifferByStyle() { @@ -130,9 +114,61 @@ class GrpcWebCompatibilityGateTest { .contains("envoy.filters.http.grpc_web"); } + @Test + void theReferenceProxyExposesEveryTrailerThePlatformSends() { + // when + Set exposed = headerList(resource("envoy/envoy.yaml"), "expose_headers"); + + // then + assertThat(exposed) + .contains( + "grpc-status", + "grpc-message", + "grpc-status-details-bin", + GrpcErrorMapper.REASON_KEY.name(), + GrpcErrorMapper.EXECUTION_ID_KEY.name(), + GrpcErrorMapper.COMPLETION_OUTCOME_KEY.name(), + GrpcValidationInterceptor.VIOLATIONS_KEY.name()); + } + + @Test + void theReferenceProxyLetsTheBrowserSendItsDeadlineAndClientHeaders() { + // when + Set allowed = headerList(resource("envoy/envoy.yaml"), "allow_headers"); + + // then + assertThat(allowed).contains("grpc-timeout", "x-user-agent", "x-grpc-web", "content-type"); + } + + @Test + void theReferenceRouteLeavesStreamLengthToTheCallersDeadline() { + // when + String envoy = resource("envoy/envoy.yaml"); + + // then + assertThat(envoy).contains("timeout: 0s").contains("grpc_timeout_header_max: 0s"); + } + + @Test + void theReferenceProxyTerminatesTlsWithACertificate() { + // when + String envoy = resource("envoy/envoy.yaml"); + + // then + assertThat(envoy).contains("certificate_chain:").contains("private_key:"); + } + + private static Set headerList(String envoy, String field) { + Matcher matcher = Pattern.compile(field + ": \"([^\"]*)\"").matcher(envoy); + if (!matcher.find()) { + throw new IllegalStateException("the reference proxy has no " + field); + } + return Set.of(matcher.group(1).split(",")); + } + private static String resource(String path) { try (InputStream stream = - GrpcWebCompatibilityGateTest.class.getClassLoader().getResourceAsStream(path)) { + GrpcWebCompatibilityTest.class.getClassLoader().getResourceAsStream(path)) { if (stream == null) { throw new IllegalStateException("missing resource " + path); } diff --git a/grpc-advanced/grpc-advanced-compat/src/main/resources/envoy/envoy.yaml b/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml similarity index 78% rename from grpc-advanced/grpc-advanced-compat/src/main/resources/envoy/envoy.yaml rename to grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml index 0c5ec86..ae3cab3 100644 --- a/grpc-advanced/grpc-advanced-compat/src/main/resources/envoy/envoy.yaml +++ b/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml @@ -29,13 +29,18 @@ static_resources: - match: { prefix: "/" } route: cluster: grpc_backend - timeout: 30s + # 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-correlation-id,authorization" - expose_headers: "grpc-status,grpc-message,error-code,error-category" + 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 @@ -51,6 +56,11 @@ static_resources: 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 diff --git a/grpc-advanced/grpc-advanced-diagnostics/build.gradle b/grpc-advanced/grpc-advanced-diagnostics/build.gradle deleted file mode 100644 index e9cb9d0..0000000 --- a/grpc-advanced/grpc-advanced-diagnostics/build.gradle +++ /dev/null @@ -1,12 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Channelz/CSDS diagnostics for administrators, with the redactor that keeps socket authority, -// credentials, certificate material, metadata and payload out of a snapshot, plus the advanced -// infrastructure testkit contract (gRPC-Web proxy, Servlet container, xDS control-plane failure). -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-client') - api project(':grpc-advanced:grpc-advanced-bootstrap') -} diff --git a/grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcAdvancedInfrastructureTestkit.java b/grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcAdvancedInfrastructureTestkit.java deleted file mode 100644 index 53a0a5d..0000000 --- a/grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcAdvancedInfrastructureTestkit.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.grpc.advanced.diagnostics; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; - -/** - * What an advanced capability has to be exercised against before it counts as verified. - * - *

Real infrastructure, named per capability. gRPC-Web without a proxy tests a code path no - * browser will take; a Servlet profile without a container tests the profile object; xDS without a - * control plane cannot exercise the case that matters, which is the control plane going away. In - * all three, a suite that runs without the infrastructure passes and establishes nothing, which is - * worse than not having one. - */ -public final class GrpcAdvancedInfrastructureTestkit { - - private GrpcAdvancedInfrastructureTestkit() {} - - /** A piece of infrastructure a capability's suite needs. */ - public enum Infrastructure { - /** An Envoy or equivalent gRPC-Web proxy. */ - GRPC_WEB_PROXY, - /** A Servlet container serving HTTP/2. */ - SERVLET_CONTAINER, - /** An xDS control plane that can be stopped. */ - XDS_CONTROL_PLANE, - /** A Kotlin toolchain. */ - KOTLIN_TOOLCHAIN - } - - /** What {@code capability} needs before its evidence means anything. */ - public static Set requiredFor(GrpcAdvancedCapability capability) { - if (capability == null) { - throw new IllegalArgumentException("a capability is required"); - } - return switch (capability) { - case GRPC_WEB -> Set.of(Infrastructure.GRPC_WEB_PROXY); - case SERVLET_COMPAT -> Set.of(Infrastructure.SERVLET_CONTAINER); - case XDS -> Set.of(Infrastructure.XDS_CONTROL_PLANE); - case KOTLIN -> Set.of(Infrastructure.KOTLIN_TOOLCHAIN); - case EDITION_2024, - EDITION_2026, - CLIENT_STREAMING, - BIDI_STREAMING, - MANUAL_FLOW_CONTROL, - HEDGING, - CUSTOM_RESOLVER, - CUSTOM_LOAD_BALANCER, - INTEGRATION_BRIDGE, - REACTOR, - CHANNEL_DIAGNOSTICS -> - Set.of(); - }; - } - - /** - * Every piece of infrastructure a capability needs and does not have. - * - * @return an empty list when the suite can produce evidence that means something - */ - public static List missingInfrastructure( - GrpcAdvancedCapability capability, Set available) { - if (available == null) { - throw new IllegalArgumentException("the available infrastructure set is required"); - } - Set required = requiredFor(capability); - if (required.isEmpty()) { - return List.of(); - } - Set missing = EnumSet.copyOf(required); - missing.removeAll(available); - List gaps = new ArrayList<>(); - missing.stream() - .sorted() - .forEach( - infrastructure -> - gaps.add( - capability.flagName() - + " needs " - + infrastructure - + "; a suite that runs without it passes and establishes nothing")); - return List.copyOf(gaps); - } -} diff --git a/grpc-advanced/grpc-advanced-edition/build.gradle b/grpc-advanced/grpc-advanced-edition/build.gradle deleted file mode 100644 index bbf33e2..0000000 --- a/grpc-advanced/grpc-advanced-edition/build.gradle +++ /dev/null @@ -1,12 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Protobuf Edition lanes. Edition 2024 is an opt-in Advanced lane that must produce cross-consumer -// compile evidence before anything public moves onto it; Edition 2026 is a watch lane that records -// release/toolchain status and is refused as a Stable contract source. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-proto-contract') - api project(':grpc-advanced:grpc-advanced-bootstrap') -} diff --git a/grpc-advanced/grpc-advanced-edition/gradle.lockfile b/grpc-advanced/grpc-advanced-edition/gradle.lockfile deleted file mode 100644 index e2c9585..0000000 --- a/grpc-advanced/grpc-advanced-edition/gradle.lockfile +++ /dev/null @@ -1,84 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.21.0=spotbugs -info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle -org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle -org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle -org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath -org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle -org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle -org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle -org.codehaus.plexus:plexus-utils:3.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit:junit-bom:6.1.0=spotbugs -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath -org.ow2.asm:asm-analysis:9.10.1=spotbugs -org.ow2.asm:asm-commons:9.10.1=spotbugs -org.ow2.asm:asm-tree:9.10.1=spotbugs -org.ow2.asm:asm-util:9.10.1=spotbugs -org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath diff --git a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Gate.java b/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Gate.java deleted file mode 100644 index 45d44d0..0000000 --- a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Gate.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -import java.util.ArrayList; -import java.util.List; - -/** - * Decides whether Edition 2024 may be adopted, and keeps its failures out of the Stable release. - * - *

The separation the Stable plan asks for, in one place: an Edition 2024 failure blocks the - * edition's own promotion and does not block a proto3 release. Without that split, an opt-in lane - * that nobody depends on can hold up every release, and the first response to that is to stop - * running the lane. - */ -public final class GrpcEdition2024Gate { - - private GrpcEdition2024Gate() {} - - /** - * Every reason Edition 2024 may not be promoted. - * - * @return an empty list when the edition is ready to adopt - */ - public static List promotionBlockers( - GrpcEditionCompatibilityReport report, - boolean consumerMigrationPlanned, - boolean promotionAdr) { - if (report == null) { - throw new IllegalArgumentException("a compatibility report is required"); - } - List blockers = new ArrayList<>(report.incompatibilities()); - if (!consumerMigrationPlanned) { - blockers.add( - "no consumer migration is planned; moving a public service to an edition breaks whichever " - + "consumer's generator treats its features differently"); - } - if (!promotionAdr) { - blockers.add( - "no promotion ADR records the decision to move onto Edition " - + GrpcEdition2024Policy.EDITION); - } - return List.copyOf(blockers); - } - - /** - * Whether an Edition 2024 failure blocks a proto3 Stable release. - * - *

Always false. Stated as a method so the property is tested rather than described. - */ - public static boolean blocksStableRelease() { - return false; - } - - /** - * Whether an Edition 2024 failure blocks the edition's own promotion. - * - *

Always true, for the same reason. - */ - public static boolean blocksEditionPromotion() { - return true; - } -} diff --git a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Guard.java b/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Guard.java deleted file mode 100644 index 3b9aab0..0000000 --- a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Guard.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.grpc.advanced.edition; - -/** - * Refuses Edition 2026 as a schema source, whatever a report says. - * - *

The guard is deliberately not conditional on the watch report. A watch lane's purpose is to - * record what is true, and letting the same record also authorise use means the moment somebody - * marks four fields SUPPORTED, a schema can move onto an edition with no promotion decision, no - * consumer migration and no ADR. Turning the watch into a lane that can be used is a code change - * here, and that is the point. - */ -public final class GrpcEdition2026Guard { - - private GrpcEdition2026Guard() {} - - /** Whether Edition 2026 may be used as a Stable contract source. Always false. */ - public static boolean allowedAsStableSource() { - return false; - } - - /** - * Fails when Edition 2026 is used as a schema source. - * - * @throws IllegalStateException naming what is still outstanding, so the refusal is actionable - */ - public static void requireNotUsedAsSource(GrpcEdition2026WatchReport report) { - if (report == null) { - throw new IllegalArgumentException("a watch report is required"); - } - throw new IllegalStateException( - "Edition " - + GrpcEdition2026WatchReport.EDITION - + " is a watch lane, not a schema source" - + (report.outstanding().isEmpty() - ? "; every toolchain gate is satisfied, so the next step is a promotion decision " - + "rather than a schema change" - : "; outstanding: " + report.outstanding())); - } - - /** - * Whether an Edition 2026 CI failure blocks the Stable build. - * - *

False. A watch lane that can break the build is a watch lane somebody deletes. - */ - public static boolean blocksStableBuild() { - return false; - } -} diff --git a/grpc-advanced/grpc-advanced-resilience/build.gradle b/grpc-advanced/grpc-advanced-resilience/build.gradle deleted file mode 100644 index 1e56b2d..0000000 --- a/grpc-advanced/grpc-advanced-resilience/build.gradle +++ /dev/null @@ -1,13 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Resilience and discovery capabilities that Stable refuses: read-only unary hedging, the custom -// name resolver SPI, the custom load balancer SPI, and the proxyless xDS experimental profile. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-policy') - api project(':grpc:grpc-client') - api project(':grpc:grpc-discovery') - api project(':grpc-advanced:grpc-advanced-bootstrap') -} diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsStartupGuard.java b/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsStartupGuard.java deleted file mode 100644 index eea0e5b..0000000 --- a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsStartupGuard.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.grpc.advanced.xds; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedFeatureFlags; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedModuleGuard; -import java.util.ArrayList; -import java.util.List; - -/** - * Refuses to start an xDS channel that is not fully configured, and refuses to let xDS be described - * as Stable support. - * - *

The second refusal is the one worth having in code. xDS working in a deployment is not the - * same claim as the platform supporting it: it brings a control plane, its outage modes, its own - * security boundary and its own version skew, and the Stable support statement covers DNS and - * static targets. A support matrix that quietly widens is a support matrix nobody can rely on. - */ -public final class GrpcXdsStartupGuard { - - private GrpcXdsStartupGuard() {} - - /** - * Every reason an xDS channel may not start. - * - * @return an empty list when the profile and flags permit it - */ - public static List startupBlockers( - GrpcXdsProfile profile, GrpcAdvancedFeatureFlags flags, boolean applicationDefinesRetries) { - if (profile == null || flags == null) { - throw new IllegalArgumentException("startup validation needs a profile and the flags"); - } - List blockers = new ArrayList<>(); - if (!GrpcAdvancedModuleGuard.available(flags, GrpcAdvancedCapability.XDS)) { - blockers.add( - "the xds capability is not available; it is " - + flags.gradeOf(GrpcAdvancedCapability.XDS) - + " and " - + (flags.flagSet(GrpcAdvancedCapability.XDS) - ? "production has not approved it" - : "its flag is not set")); - } - if (applicationDefinesRetries) { - blockers.add( - "the application also defines retry policy; with xDS the control plane owns it, and " - + "defining it in both places makes the winner depend on resolution order"); - } - return List.copyOf(blockers); - } - - /** - * Every disagreement between a deployment's profile and the bootstrap file its client will read. - * - *

Checked because the two are written by different people in different repositories, and the - * failure is silent: a client whose bootstrap names a namespace the deployment did not configure - * subscribes successfully and receives another team's routing. Nothing errors — the control plane - * answers, the resources parse, and traffic goes somewhere nobody chose. - * - *

Matched textually rather than with a JSON parser, deliberately. This leaf's test classpath - * is plain JUnit and AssertJ, and adding a JSON library to check three fields would put a parser - * on the runtime classpath of every deployment that enables xDS. - * - * @param bootstrapJson the bootstrap document's contents - * @return an empty list when the bootstrap and the profile agree - */ - public static List bootstrapMismatches(GrpcXdsProfile profile, String bootstrapJson) { - if (profile == null) { - throw new IllegalArgumentException("a profile is required"); - } - if (bootstrapJson == null || bootstrapJson.isBlank()) { - throw new IllegalArgumentException( - "the bootstrap document is required; a client with no bootstrap has no control plane to ask"); - } - List mismatches = new ArrayList<>(); - if (!bootstrapJson.contains("\"xds_servers\"")) { - mismatches.add("the bootstrap declares no xds_servers"); - } - if (!bootstrapJson.contains("\"channel_creds\"") || !bootstrapJson.contains("\"tls\"")) { - mismatches.add( - "the bootstrap's control-plane channel is not TLS; that connection carries routing and " - + "often certificates, so an unauthenticated one can be impersonated"); - } - if (!bootstrapJson.contains(profile.resourceNamespace())) { - mismatches.add( - "the bootstrap does not name the profile's resource namespace '" - + profile.resourceNamespace() - + "'; a client that subscribes outside its namespace receives another team's routing, " - + "and nothing about that fails"); - } - return List.copyOf(mismatches); - } - - /** - * Whether xDS may be advertised as part of Stable discovery support. - * - *

Always false. Stable support is DNS and static. - */ - public static boolean advertisableAsStableSupport() { - return false; - } -} diff --git a/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsStartupGuardTest.java b/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsStartupGuardTest.java deleted file mode 100644 index 3e03900..0000000 --- a/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsStartupGuardTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package dev.caskeleton.grpc.advanced.resilience; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedCapability; -import dev.caskeleton.grpc.advanced.bootstrap.GrpcAdvancedFeatureFlags; -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.advanced.xds.GrpcXdsStartupGuard; -import dev.caskeleton.grpc.resilience.GrpcRetryOwner; -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcXdsStartupGuardTest { - - 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("hyeonworks/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("xDS needs its capability approved and refuses duplicate retry ownership") - void startupRequiresApprovalAndSingleRetryOwner() { - GrpcAdvancedFeatureFlags unapproved = - GrpcAdvancedFeatureFlags.forProduction(Set.of()).enable(GrpcAdvancedCapability.XDS); - GrpcAdvancedFeatureFlags approved = - GrpcAdvancedFeatureFlags.forProduction(Set.of(GrpcAdvancedCapability.XDS)) - .enable(GrpcAdvancedCapability.XDS); - - assertThat( - GrpcXdsStartupGuard.startupBlockers(profile("hyeonworks/documents"), unapproved, false)) - .anySatisfy(blocker -> assertThat(blocker).contains("production has not approved it")); - assertThat( - GrpcXdsStartupGuard.startupBlockers(profile("hyeonworks/documents"), approved, false)) - .isEmpty(); - assertThat(GrpcXdsStartupGuard.startupBlockers(profile("hyeonworks/documents"), approved, true)) - .anySatisfy(blocker -> assertThat(blocker).contains("resolution order")); - } - - @Test - @DisplayName("an unflagged capability is reported as unflagged rather than unapproved") - void anUnflaggedCapabilityIsReportedAsSuch() { - assertThat( - GrpcXdsStartupGuard.startupBlockers( - profile("hyeonworks/documents"), - GrpcAdvancedFeatureFlags.forProduction(Set.of()), - false)) - .anySatisfy(blocker -> assertThat(blocker).contains("its flag is not set")); - } - - @Test - @DisplayName("the committed bootstrap fixture agrees with the profile it is meant to serve") - void theBootstrapFixtureAgreesWithItsProfile() { - assertThat( - GrpcXdsStartupGuard.bootstrapMismatches( - profile("hyeonworks/documents"), resource("xds/bootstrap.json"))) - .isEmpty(); - } - - @Test - @DisplayName("a bootstrap naming another namespace is reported, since nothing else would fail") - void aNamespaceMismatchIsReported() { - assertThat( - GrpcXdsStartupGuard.bootstrapMismatches( - profile("hyeonworks/billing"), resource("xds/bootstrap.json"))) - .anySatisfy(mismatch -> assertThat(mismatch).contains("another team's routing")); - } - - @Test - @DisplayName("a bootstrap with an unauthenticated control-plane channel is reported") - void anUnauthenticatedControlPlaneIsReported() { - String insecure = - resource("xds/bootstrap.json") - .replace("{ \"type\": \"tls\" }", "{ \"type\": \"insecure\" }"); - - assertThat(GrpcXdsStartupGuard.bootstrapMismatches(profile("hyeonworks/documents"), insecure)) - .anySatisfy(mismatch -> assertThat(mismatch).contains("can be impersonated")); - } - - @Test - @DisplayName("a missing bootstrap is refused rather than treated as an empty one") - void aMissingBootstrapIsRefused() { - assertThatThrownBy( - () -> GrpcXdsStartupGuard.bootstrapMismatches(profile("hyeonworks/documents"), " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("no control plane to ask"); - } - - @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"); - } - - @Test - @DisplayName("xDS is not part of the Stable discovery support statement") - void xdsIsNotStableSupport() { - assertThat(GrpcXdsStartupGuard.advertisableAsStableSupport()).isFalse(); - } - - private static String resource(String path) { - try (InputStream stream = - GrpcXdsStartupGuardTest.class.getClassLoader().getResourceAsStream(path)) { - if (stream == null) { - throw new IllegalStateException("missing test resource " + path); - } - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/grpc-advanced/grpc-advanced-resilience/src/test/resources/xds/bootstrap.json b/grpc-advanced/grpc-advanced-resilience/src/test/resources/xds/bootstrap.json deleted file mode 100644 index d118a07..0000000 --- a/grpc-advanced/grpc-advanced-resilience/src/test/resources/xds/bootstrap.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "_comment": [ - "An xDS bootstrap fixture. The client reads this file to learn where its control plane is and", - "who it claims to be; GrpcXdsProfile validates the deployment settings that must agree with it.", - "The two fields the profile actually checks against are server_uri (the control plane must be", - "reached over authenticated mTLS) and the node id's namespace (a client that subscribes outside", - "its namespace receives another team's routing)." - ], - "xds_servers": [ - { - "server_uri": "xds-control-plane.hyeonworks.internal:15010", - "channel_creds": [ - { "type": "tls" } - ], - "server_features": ["xds_v3"] - } - ], - "node": { - "id": "hyeonworks/documents/documents-7f9c4", - "cluster": "documents", - "metadata": { - "NAMESPACE": "hyeonworks/documents" - }, - "locality": { - "region": "ap-northeast-2", - "zone": "ap-northeast-2a" - } - }, - "authorities": { - "hyeonworks.internal": { - "xds_servers": [ - { - "server_uri": "xds-control-plane.hyeonworks.internal:15010", - "channel_creds": [{ "type": "tls" }], - "server_features": ["xds_v3"] - } - ] - } - } -} diff --git a/grpc-advanced/grpc-advanced-streaming/build.gradle b/grpc-advanced/grpc-advanced-streaming/build.gradle deleted file mode 100644 index 2e5bbbd..0000000 --- a/grpc-advanced/grpc-advanced-streaming/build.gradle +++ /dev/null @@ -1,12 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// The streaming shapes the Stable plan deliberately excludes: client streaming sessions with -// dedup/checkpoint/resume, bidirectional sessions with independent per-direction sequences, and the -// manual flow-control approval API. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-policy') - api project(':grpc-advanced:grpc-advanced-bootstrap') -} diff --git a/grpc-advanced/grpc-advanced-streaming/gradle.lockfile b/grpc-advanced/grpc-advanced-streaming/gradle.lockfile deleted file mode 100644 index 9369e83..0000000 --- a/grpc-advanced/grpc-advanced-streaming/gradle.lockfile +++ /dev/null @@ -1,91 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.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= diff --git a/grpc-advanced/grpc-advanced/build.gradle b/grpc-advanced/grpc-advanced/build.gradle new file mode 100644 index 0000000..c4b9a18 --- /dev/null +++ b/grpc-advanced/grpc-advanced/build.gradle @@ -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') +} diff --git a/grpc-advanced/grpc-advanced-diagnostics/gradle.lockfile b/grpc-advanced/grpc-advanced/gradle.lockfile similarity index 100% rename from grpc-advanced/grpc-advanced-diagnostics/gradle.lockfile rename to grpc-advanced/grpc-advanced/gradle.lockfile diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java similarity index 95% rename from grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java index b679f14..12e8fb6 100644 --- a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java +++ b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapability.java @@ -48,14 +48,14 @@ public enum GrpcAdvancedCapability { this.defaultGrade = defaultGrade; } - /** The property suffix under {@code ca-skeleton.grpc.advanced}. */ + /** 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 "ca-skeleton.grpc.advanced." + flagName + ".enabled"; + return "app.grpc.advanced." + flagName + ".enabled"; } /** How ready this capability is today. */ diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapabilityDisabledException.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapabilityDisabledException.java similarity index 100% rename from grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapabilityDisabledException.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedCapabilityDisabledException.java diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedFeatureFlags.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedFeatureFlags.java similarity index 100% rename from grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedFeatureFlags.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedFeatureFlags.java diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java similarity index 75% rename from grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java index 4a510f4..6d82779 100644 --- a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java +++ b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java @@ -1,9 +1,5 @@ package dev.caskeleton.grpc.advanced.bootstrap; -import dev.caskeleton.grpc.core.GrpcStableBuildInvariant; -import dev.caskeleton.grpc.core.GrpcStableModuleCatalog; -import java.util.Set; - /** * The single gate every advanced capability passes through. * @@ -65,20 +61,4 @@ public final class GrpcAdvancedModuleGuard { + "that somebody accepted its uncharacterised failure modes"); } } - - /** - * Fails when the Stable starter's dependency set reaches an advanced module. - * - *

The same invariant the registry enforces at build time, asserted here so a runtime that was - * assembled some other way — a fat jar, a shaded artifact, a test harness — is checked too. - */ - public static void requireStableStarterIsClean(Set starterDependencies) { - GrpcStableBuildInvariant.requireNoAdvancedDependency( - "grpc-spring-boot-starter", starterDependencies); - } - - /** The advanced module ids, for a runtime classpath check. */ - public static Set advancedModules() { - return GrpcStableModuleCatalog.advancedModules(); - } } diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcCapabilityGrade.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcCapabilityGrade.java similarity index 100% rename from grpc-advanced/grpc-advanced-bootstrap/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcCapabilityGrade.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcCapabilityGrade.java diff --git a/grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicy.java similarity index 100% rename from grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicy.java diff --git a/grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsSnapshot.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsSnapshot.java similarity index 100% rename from grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsSnapshot.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsSnapshot.java diff --git a/grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactor.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactor.java similarity index 100% rename from grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactor.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactor.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcCustomResolver.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcCustomResolver.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcCustomResolver.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcCustomResolver.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointCandidate.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointCandidate.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointCandidate.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointCandidate.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointSnapshot.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointSnapshot.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointSnapshot.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcEndpointSnapshot.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerDecision.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerDecision.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerDecision.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerDecision.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerPicker.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerPicker.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerPicker.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerPicker.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerSafetyPolicy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerSafetyPolicy.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerSafetyPolicy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcLoadBalancerSafetyPolicy.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java similarity index 54% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java index 0727a2f..95bd0bd 100644 --- a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java +++ b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java @@ -2,7 +2,9 @@ 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; /** @@ -19,8 +21,14 @@ public final class GrpcResolverSafetyPolicy { private static final Pattern AUTHORITY = Pattern.compile("[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\\d{1,5})?"); - private static final Pattern CREDENTIAL_SHAPED = - Pattern.compile("(?i).*(authorization|bearer|password|secret|token|api[_-]?key).*"); + /** The top-level fields of a gRPC service config. Anything else is not policy. */ + private static final Set SERVICE_CONFIG_FIELDS = + Set.of( + "loadBalancingConfig", + "loadBalancingPolicy", + "methodConfig", + "retryThrottling", + "healthCheckConfig"); private GrpcResolverSafetyPolicy() {} @@ -53,40 +61,40 @@ public final class GrpcResolverSafetyPolicy { + (lastAccepted == null ? "none" : lastAccepted.revision()) + "; applying it would replace newer endpoints with older ones"); } - update - .serviceConfigJson() - .ifPresent( - config -> { - if (CREDENTIAL_SHAPED.matcher(config).find()) { - violations.add( - "the pushed service config contains a credential-shaped field; a resolver " - + "supplies addresses and policy, never authentication material"); - } - }); + update.serviceConfig().ifPresent(config -> serviceConfigViolations(config, violations)); return List.copyOf(violations); } - /** - * Whether a closed resolver's update should be applied. - * - *

Always false. A resolver that keeps delivering after close is one whose discovery source has - * not noticed the channel is gone, and applying its updates resurrects routing for a channel - * nobody is using. - */ - public static boolean acceptAfterClose() { - return false; - } - - /** Whether a resolver may supply caller identity or business metadata. Always false. */ - public static boolean mayCarryBusinessMetadata() { - return false; + private static void serviceConfigViolations(Map config, List violations) { + if (!SERVICE_CONFIG_FIELDS.containsAll(config.keySet())) { + violations.add( + "the pushed service config has top-level fields outside " + + SERVICE_CONFIG_FIELDS.stream().sorted().toList() + + "; a resolver supplies addresses and policy, never authentication material"); + } + Object methodConfig = config.get("methodConfig"); + if (methodConfig == null) { + return; + } + if (!(methodConfig instanceof List entries) + || !entries.stream().allMatch(entry -> entry instanceof Map)) { + violations.add("the pushed service config's methodConfig is not a list of objects"); + return; + } + if (entries.stream() + .map(entry -> (Map) entry) + .anyMatch( + entry -> entry.containsKey("retryPolicy") || entry.containsKey("hedgingPolicy"))) { + violations.add( + "the pushed service config sets retryPolicy or hedgingPolicy; retries and hedging are " + + "owned by the platform's method policy catalog, and a resolver that could turn them " + + "on could retry a non-idempotent method from outside the codebase"); + } } /** The service config an update may contribute, once validated. */ - public static Optional acceptedServiceConfig( + public static Optional> acceptedServiceConfig( GrpcResolverUpdate update, GrpcEndpointSnapshot lastAccepted) { - return violations(update, lastAccepted).isEmpty() - ? update.serviceConfigJson() - : Optional.empty(); + return violations(update, lastAccepted).isEmpty() ? update.serviceConfig() : Optional.empty(); } } diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java similarity index 57% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java index 1a3bfb2..d09cf36 100644 --- a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java +++ b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverUpdate.java @@ -1,5 +1,8 @@ package dev.caskeleton.grpc.advanced.discovery; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Optional; /** @@ -11,20 +14,26 @@ import java.util.Optional; * anyone reviewed it. */ public record GrpcResolverUpdate( - GrpcEndpointSnapshot snapshot, Optional serviceConfigJson) { + GrpcEndpointSnapshot snapshot, Optional> serviceConfig) { - /** Requires a snapshot and the Optional. */ + /** + * Requires a snapshot and the Optional. The service config is the parsed JSON object, the same + * {@code Map} shape gRPC's {@code NameResolver.Helper.parseServiceConfig} takes; it is + * copied so it cannot change between validation and delivery. + */ public GrpcResolverUpdate { - if (snapshot == null || serviceConfigJson == null) { + if (snapshot == null || serviceConfig == null) { throw new IllegalArgumentException("a resolver update carries a snapshot and the Optional"); } - serviceConfigJson.ifPresent( + serviceConfig.ifPresent( config -> { - if (config.isBlank()) { + if (config.isEmpty()) { throw new IllegalArgumentException( - "a present service config must not be blank; absent and empty are different states"); + "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. */ diff --git a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Policy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Policy.java similarity index 100% rename from grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Policy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Policy.java diff --git a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Status.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Status.java similarity index 100% rename from grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Status.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Status.java diff --git a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReport.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReport.java similarity index 100% rename from grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReport.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReport.java diff --git a/grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEditionCompatibilityReport.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEditionCompatibilityReport.java similarity index 100% rename from grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEditionCompatibilityReport.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEditionCompatibilityReport.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingBudget.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingBudget.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingBudget.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingBudget.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibility.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibility.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibility.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibility.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingPolicy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingPolicy.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingPolicy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingPolicy.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingResult.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingResult.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingResult.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingResult.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiDirectionState.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiDirectionState.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiDirectionState.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiDirectionState.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiResumeState.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiResumeState.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiResumeState.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiResumeState.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTracker.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTracker.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTracker.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTracker.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSession.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSession.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSession.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSession.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicator.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicator.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicator.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicator.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamCheckpoint.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamCheckpoint.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamCheckpoint.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamCheckpoint.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamMessage.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamMessage.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamMessage.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamMessage.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicy.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicy.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamResumeDecision.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamResumeDecision.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamResumeDecision.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamResumeDecision.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamSessionId.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamSessionId.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamSessionId.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamSessionId.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamState.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamState.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamState.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamState.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandController.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandController.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandController.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandController.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandDecision.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandDecision.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandDecision.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandDecision.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcManualFlowControlPolicy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcManualFlowControlPolicy.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcManualFlowControlPolicy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/streaming/GrpcManualFlowControlPolicy.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsFailurePolicy.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsFailurePolicy.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsFailurePolicy.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsFailurePolicy.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsProfile.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsProfile.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsProfile.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsProfile.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsResourceSnapshot.java b/grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsResourceSnapshot.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsResourceSnapshot.java rename to grpc-advanced/grpc-advanced/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsResourceSnapshot.java diff --git a/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java similarity index 84% rename from grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java index 9f53e67..32268e9 100644 --- a/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java +++ b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java @@ -23,8 +23,7 @@ class GrpcAdvancedModuleGuardTest { @Test @DisplayName("each capability has its own flag, not a shared one") void eachCapabilityHasItsOwnFlag() { - assertThat(GrpcAdvancedCapability.XDS.propertyKey()) - .isEqualTo("ca-skeleton.grpc.advanced.xds.enabled"); + assertThat(GrpcAdvancedCapability.XDS.propertyKey()).isEqualTo("app.grpc.advanced.xds.enabled"); assertThat(GrpcAdvancedCapability.GRPC_WEB.propertyKey()) .isNotEqualTo(GrpcAdvancedCapability.XDS.propertyKey()); @@ -43,7 +42,7 @@ class GrpcAdvancedModuleGuardTest { GrpcAdvancedModuleGuard.require( GrpcAdvancedFeatureFlags.forDevelopment(), GrpcAdvancedCapability.REACTOR)) .isInstanceOf(GrpcAdvancedCapabilityDisabledException.class) - .hasMessageContaining("ca-skeleton.grpc.advanced.reactor.enabled=true"); + .hasMessageContaining("app.grpc.advanced.reactor.enabled=true"); } @Test @@ -89,21 +88,6 @@ class GrpcAdvancedModuleGuardTest { GrpcAdvancedModuleGuard.require(flags, GrpcAdvancedCapability.HEDGING); } - @Test - @DisplayName("the Stable starter reaching an advanced module is refused") - void theStableStarterMayNotReachAnAdvancedModule() { - GrpcAdvancedModuleGuard.requireStableStarterIsClean(Set.of("grpc-core-api", "grpc-policy")); - - assertThatThrownBy( - () -> - GrpcAdvancedModuleGuard.requireStableStarterIsClean( - Set.of("grpc-core-api", "grpc-advanced-resilience"))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("grpc-advanced-resilience"); - assertThat(GrpcAdvancedModuleGuard.advancedModules()) - .contains("grpc-advanced-bootstrap", "grpc-advanced-streaming", "grpc-advanced-compat"); - } - @Test @DisplayName("only flagged and permitted capabilities appear as active") void activeReflectsBothFlagAndGrade() { diff --git a/grpc-advanced/grpc-advanced-diagnostics/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java similarity index 85% rename from grpc-advanced/grpc-advanced-diagnostics/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java index c537ba7..e5a0a2c 100644 --- a/grpc-advanced/grpc-advanced-diagnostics/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java +++ b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java @@ -191,36 +191,6 @@ class GrpcChannelDiagnosticsPolicyTest { assertThat(snapshot.xdsResourceVersions()).hasSize(3); } - @Test - @DisplayName("each capability names the real infrastructure its evidence depends on") - void capabilitiesNameTheirInfrastructure() { - assertThat(GrpcAdvancedInfrastructureTestkit.requiredFor(GrpcAdvancedCapability.GRPC_WEB)) - .containsExactly(GrpcAdvancedInfrastructureTestkit.Infrastructure.GRPC_WEB_PROXY); - assertThat(GrpcAdvancedInfrastructureTestkit.requiredFor(GrpcAdvancedCapability.XDS)) - .containsExactly(GrpcAdvancedInfrastructureTestkit.Infrastructure.XDS_CONTROL_PLANE); - assertThat(GrpcAdvancedInfrastructureTestkit.requiredFor(GrpcAdvancedCapability.HEDGING)) - .isEmpty(); - } - - @Test - @DisplayName("a suite without its infrastructure is reported as establishing nothing") - void missingInfrastructureIsReported() { - assertThat( - GrpcAdvancedInfrastructureTestkit.missingInfrastructure( - GrpcAdvancedCapability.XDS, Set.of())) - .singleElement() - .satisfies(gap -> assertThat(gap).contains("establishes nothing")); - assertThat( - GrpcAdvancedInfrastructureTestkit.missingInfrastructure( - GrpcAdvancedCapability.XDS, - Set.of(GrpcAdvancedInfrastructureTestkit.Infrastructure.XDS_CONTROL_PLANE))) - .isEmpty(); - assertThat( - GrpcAdvancedInfrastructureTestkit.missingInfrastructure( - GrpcAdvancedCapability.HEDGING, Set.of())) - .isEmpty(); - } - private static String resource(String path) { try (java.io.InputStream stream = GrpcChannelDiagnosticsPolicyTest.class.getClassLoader().getResourceAsStream(path)) { diff --git a/grpc-advanced/grpc-advanced-diagnostics/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactorIdempotenceTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactorIdempotenceTest.java similarity index 100% rename from grpc-advanced/grpc-advanced-diagnostics/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactorIdempotenceTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcDiagnosticsRedactorIdempotenceTest.java diff --git a/grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024GateTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java similarity index 64% rename from grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024GateTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java index e13d839..00b6f3e 100644 --- a/grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024GateTest.java +++ b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java @@ -12,7 +12,7 @@ import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -class GrpcEdition2024GateTest { +class GrpcEdition2024PolicyTest { private static GrpcEditionCompatibilityReport report( boolean wire, boolean json, Map toolchains) { @@ -24,10 +24,10 @@ class GrpcEdition2024GateTest { void editionIsOptInPerModule() { GrpcEdition2024Policy policy = GrpcEdition2024Policy.notAdopted(); - assertThat(policy.allowedIn("grpc-proto-contract")).isFalse(); + assertThat(policy.allowedIn("grpc-contract")).isFalse(); assertThat( - new GrpcEdition2024Policy(Set.of("grpc-advanced-edition"), Set.of(), false) - .allowedIn("grpc-advanced-edition")) + new GrpcEdition2024Policy(Set.of("grpc-advanced"), Set.of(), false) + .allowedIn("grpc-advanced")) .isTrue(); } @@ -36,18 +36,14 @@ class GrpcEdition2024GateTest { void publicServicesNeedAPromotion() { GrpcEdition2024Policy withoutPromotion = new GrpcEdition2024Policy( - Set.of("grpc-advanced-edition"), - Set.of("hyeonworks.document.v1.DocumentService"), - false); + Set.of("grpc-advanced"), Set.of("caskeleton.document.v1.DocumentService"), false); GrpcEdition2024Policy withPromotion = new GrpcEdition2024Policy( - Set.of("grpc-advanced-edition"), - Set.of("hyeonworks.document.v1.DocumentService"), - true); + Set.of("grpc-advanced"), Set.of("caskeleton.document.v1.DocumentService"), true); - assertThat(withoutPromotion.serviceMayMove("hyeonworks.document.v1.DocumentService")).isFalse(); - assertThat(withPromotion.serviceMayMove("hyeonworks.document.v1.DocumentService")).isTrue(); - assertThat(withoutPromotion.serviceMayMove("hyeonworks.internal.v1.ScratchService")).isTrue(); + 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 @@ -74,25 +70,6 @@ class GrpcEdition2024GateTest { .satisfies(problem -> assertThat(problem).contains("browser clients")); } - @Test - @DisplayName("promotion needs compatibility, a consumer migration and an ADR") - void promotionNeedsAllThree() { - GrpcEditionCompatibilityReport clean = report(true, true, Map.of("java", true, "go", true)); - - assertThat(GrpcEdition2024Gate.promotionBlockers(clean, true, true)).isEmpty(); - assertThat(GrpcEdition2024Gate.promotionBlockers(clean, false, true)) - .anySatisfy(blocker -> assertThat(blocker).contains("consumer migration")); - assertThat(GrpcEdition2024Gate.promotionBlockers(clean, true, false)) - .anySatisfy(blocker -> assertThat(blocker).contains("promotion ADR")); - } - - @Test - @DisplayName("an Edition failure blocks the edition's promotion and not a proto3 release") - void editionFailuresAreIsolatedFromStable() { - assertThat(GrpcEdition2024Gate.blocksStableRelease()).isFalse(); - assertThat(GrpcEdition2024Gate.blocksEditionPromotion()).isTrue(); - } - @Test @DisplayName("the Edition 2024 comparison fixture ships beside its proto3 twin") void theComparisonFixtureShips() { @@ -106,7 +83,7 @@ class GrpcEdition2024GateTest { private static String resource(String path) { try (InputStream stream = - GrpcEdition2024GateTest.class.getClassLoader().getResourceAsStream(path)) { + GrpcEdition2024PolicyTest.class.getClassLoader().getResourceAsStream(path)) { if (stream == null) { throw new IllegalStateException("missing resource " + path); } diff --git a/grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026GuardTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReportTest.java similarity index 60% rename from grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026GuardTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReportTest.java index 9423d69..0f9ac3c 100644 --- a/grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026GuardTest.java +++ b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026WatchReportTest.java @@ -7,7 +7,7 @@ import java.time.Instant; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -class GrpcEdition2026GuardTest { +class GrpcEdition2026WatchReportTest { private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); @@ -55,39 +55,4 @@ class GrpcEdition2026GuardTest { assertThat(GrpcEdition2026Status.UNKNOWN.usable()).isFalse(); assertThat(GrpcEdition2026Status.UNSUPPORTED.usable()).isFalse(); } - - @Test - @DisplayName("Edition 2026 is refused as a schema source even when every gate is satisfied") - void theGuardIsNotConditionalOnTheReport() { - GrpcEdition2026WatchReport allSupported = - new GrpcEdition2026WatchReport( - GrpcEdition2026Status.SUPPORTED, - GrpcEdition2026Status.SUPPORTED, - GrpcEdition2026Status.SUPPORTED, - GrpcEdition2026Status.SUPPORTED, - NOW); - - assertThat(allSupported.readyToEvaluate()).isTrue(); - assertThat(GrpcEdition2026Guard.allowedAsStableSource()).isFalse(); - assertThatThrownBy(() -> GrpcEdition2026Guard.requireNotUsedAsSource(allSupported)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("promotion decision rather than a schema change"); - } - - @Test - @DisplayName("a refusal names what is still outstanding, so it is actionable") - void aRefusalNamesWhatIsOutstanding() { - assertThatThrownBy( - () -> - GrpcEdition2026Guard.requireNotUsedAsSource( - GrpcEdition2026WatchReport.nothingKnown(NOW))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("outstanding:"); - } - - @Test - @DisplayName("a watch lane failure does not break the Stable build") - void theWatchLaneDoesNotBlockTheStableBuild() { - assertThat(GrpcEdition2026Guard.blocksStableBuild()).isFalse(); - } } diff --git a/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java similarity index 96% rename from grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java index c0350c4..f9068f8 100644 --- a/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java +++ b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcHedgingEligibilityTest.java @@ -17,11 +17,11 @@ import org.junit.jupiter.api.Test; class GrpcHedgingEligibilityTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName WATCH = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/WatchDocuments"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); private static final GrpcDeadlineProfile TWO_SECONDS = GrpcDeadlineProfile.of(Duration.ofSeconds(2)); diff --git a/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcLoadBalancerSafetyPolicyTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcLoadBalancerSafetyPolicyTest.java similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcLoadBalancerSafetyPolicyTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcLoadBalancerSafetyPolicyTest.java diff --git a/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java similarity index 72% rename from grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java index 0821a87..28da914 100644 --- a/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java +++ b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcResolverSafetyPolicyTest.java @@ -2,6 +2,7 @@ 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; @@ -9,6 +10,7 @@ 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; @@ -65,7 +67,6 @@ class GrpcResolverSafetyPolicyTest { new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1"))))) .anySatisfy(violation -> assertThat(violation).contains("resolver is closed")); assertThat(delivered).isEmpty(); - assertThat(GrpcResolverSafetyPolicy.acceptAfterClose()).isFalse(); } @Test @@ -74,11 +75,10 @@ class GrpcResolverSafetyPolicyTest { GrpcResolverUpdate withCredential = new GrpcResolverUpdate( new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of("{\"authorization\":\"Bearer abc\"}")); + Optional.of(Map.of("authorization", "Bearer abc"))); assertThat(GrpcResolverSafetyPolicy.violations(withCredential, null)) .anySatisfy(violation -> assertThat(violation).contains("never authentication material")); - assertThat(GrpcResolverSafetyPolicy.mayCarryBusinessMetadata()).isFalse(); assertThat(GrpcResolverSafetyPolicy.acceptedServiceConfig(withCredential, null)).isEmpty(); } @@ -88,12 +88,48 @@ class GrpcResolverSafetyPolicyTest { GrpcResolverUpdate clean = new GrpcResolverUpdate( new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of("{\"loadBalancingConfig\":[{\"round_robin\":{}}]}")); + Optional.of(Map.of("loadBalancingConfig", List.of(Map.of("round_robin", Map.of()))))); assertThat(GrpcResolverSafetyPolicy.violations(clean, null)).isEmpty(); assertThat(GrpcResolverSafetyPolicy.acceptedServiceConfig(clean, null)).isPresent(); } + @Test + void aServiceConfigWithRetryThrottlingIsAccepted() { + // given + GrpcResolverUpdate throttled = + new GrpcResolverUpdate( + new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), + Optional.of(Map.of("retryThrottling", Map.of("maxTokens", 10, "tokenRatio", 0.1)))); + + // when + List violations = GrpcResolverSafetyPolicy.violations(throttled, null); + + // then + assertThat(violations).isEmpty(); + } + + @Test + void aServiceConfigThatTurnsOnRetriesIsRefused() { + // given + GrpcResolverUpdate retrying = + new GrpcResolverUpdate( + new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), + Optional.of( + Map.of( + "methodConfig", + List.of( + Map.of( + "name", List.of(Map.of("service", "documents.v1.Documents")), + "retryPolicy", Map.of("maxAttempts", 5)))))); + + // when + List violations = GrpcResolverSafetyPolicy.violations(retrying, null); + + // then + assertThat(violations).singleElement().asString().contains("retryPolicy or hedgingPolicy"); + } + @Test @DisplayName("an invalid authority is refused, because it decides which certificate is accepted") void anInvalidAuthorityIsRefused() { @@ -106,14 +142,18 @@ class GrpcResolverSafetyPolicyTest { } @Test - @DisplayName("a present service config may not be blank") - void aPresentServiceConfigMayNotBeBlank() { - assertThatThrownBy( + void aPresentServiceConfigMayNotBeEmpty() { + // when + Throwable failure = + catchThrowable( () -> new GrpcResolverUpdate( new GrpcEndpointSnapshot(1L, "documents", List.of("10.0.0.1")), - Optional.of(" "))) + Optional.of(Map.of()))); + + // then + assertThat(failure) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("different states"); + .hasMessageContaining("absent and empty are different states"); } } diff --git a/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java new file mode 100644 index 0000000..4e89989 --- /dev/null +++ b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java @@ -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"); + } +} diff --git a/grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTrackerTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTrackerTest.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTrackerTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcBidiSequenceTrackerTest.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicatorTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicatorTest.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicatorTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientMessageDeduplicatorTest.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicyTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicyTest.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicyTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcClientStreamPolicyTest.java diff --git a/grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandControllerTest.java b/grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandControllerTest.java similarity index 100% rename from grpc-advanced/grpc-advanced-streaming/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandControllerTest.java rename to grpc-advanced/grpc-advanced/src/test/java/dev/caskeleton/grpc/advanced/streaming/GrpcDemandControllerTest.java diff --git a/grpc-advanced/grpc-advanced-edition/src/main/resources/proto/edition2024/compatibility.proto b/grpc-advanced/grpc-advanced/src/test/resources/proto/edition2024/compatibility.proto similarity index 80% rename from grpc-advanced/grpc-advanced-edition/src/main/resources/proto/edition2024/compatibility.proto rename to grpc-advanced/grpc-advanced/src/test/resources/proto/edition2024/compatibility.proto index 40679ad..0791ab3 100644 --- a/grpc-advanced/grpc-advanced-edition/src/main/resources/proto/edition2024/compatibility.proto +++ b/grpc-advanced/grpc-advanced/src/test/resources/proto/edition2024/compatibility.proto @@ -1,9 +1,9 @@ edition = "2024"; -package hyeonworks.grpc.edition.v1; +package caskeleton.grpc.edition.v1; option java_multiple_files = true; -option java_package = "hyeonworks.grpc.edition.v1.generated"; +option java_package = "caskeleton.grpc.edition.v1.generated"; // The Edition 2024 comparison fixture. // @@ -13,7 +13,7 @@ option java_package = "hyeonworks.grpc.edition.v1.generated"; // 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 — see GrpcEdition2024Gate. +// cross-consumer compile evidence and a promotion ADR (GrpcEdition2024Policy.promotionApproved). message DocumentSummary { string id = 1; string title = 2 [features.field_presence = EXPLICIT]; diff --git a/grpc-advanced/grpc-advanced-diagnostics/src/test/resources/xds/control-plane-snapshot.json b/grpc-advanced/grpc-advanced/src/test/resources/xds/control-plane-snapshot.json similarity index 100% rename from grpc-advanced/grpc-advanced-diagnostics/src/test/resources/xds/control-plane-snapshot.json rename to grpc-advanced/grpc-advanced/src/test/resources/xds/control-plane-snapshot.json diff --git a/grpc/CLAUDE.md b/grpc/CLAUDE.md index 766fb78..7bb05da 100644 --- a/grpc/CLAUDE.md +++ b/grpc/CLAUDE.md @@ -20,13 +20,8 @@ leaf의 정확한 id는 registry에서 읽는다. | Family | 역할 | 허용 framework | | --- | --- | --- | | `grpc-core-api` | 식별자, method policy, 실행 증거, 실패 모델, deadline, request context, operation ledger port | **Java stdlib만.** io.grpc / Spring / protobuf / DB 타입 금지 | -| `grpc-proto-contract` | `.proto` 스키마 소스와 style/schema 규칙 검증기 | Java stdlib만 | -| `grpc-codegen` | Buf governance, codegen manifest, descriptor 릴리스 아티팩트 | Java stdlib만 | -| `grpc-policy` | validation, context, status/rich error, TLS/credential, deadline/cancellation, retry, idempotency, streaming, size/compression | `io.grpc:grpc-api`, `grpc-stub`. Spring 금지 | -| `grpc-server` | application boundary rule, typed service adapter SPI, interceptor 순서, Netty profile | `io.grpc:grpc-api`, `grpc-stub`. Netty 자체 금지 — profile은 설정 모델이다 | -| `grpc-client` | named channel, runtime generation, typed stub factory, client metadata/credentials | `io.grpc:grpc-api`, `grpc-stub` | -| `grpc-discovery` | Static/DNS resolver, pick_first/round_robin, Kubernetes routing profile | Java stdlib만 | -| `grpc-admin` | health, reflection, drain, secret-free policy snapshot | Java stdlib만 | +| `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. 여기서만 | @@ -35,7 +30,16 @@ leaf의 정확한 id는 registry에서 읽는다. `grpc-core-api`가 io.grpc를 이름조차 부르지 않는다는 것이 이 family의 핵심 제약이다. 실행 증거와 실패 모델은 "전송이 무엇을 했는가"를 기술하는 계약이고, 그 계약 안에 전송 타입이 들어가면 계약이 전송의 일부가 된다. `GrpcStatusCode`가 io.grpc의 코드를 미러링하는 이유가 이것이고, 양방향 번역은 -`grpc-policy`의 `GrpcStatusMapping`이 단독으로 소유한다. +`grpc-runtime`의 `GrpcStatusMapping`이 단독으로 소유한다. + +기본 전송 한도(메시지 1 MiB, metadata 8 KiB)는 `grpc-core-api`의 `GrpcTransportLimits` 한 곳에 있고, +server profile·named channel profile·method size profile·method policy 기본값·metadata budget이 모두 +그 상수를 쓴다. `GrpcPlatformStartupValidator`는 method의 inbound 한도가 server profile 한도보다 크면 +기동을 거부한다. + +`.proto`의 proto 조직 이름은 `caskeleton`이다(`package caskeleton.grpc.common.v1`, 생성 Java 패키지 +`caskeleton.grpc.common.v1.generated` — 손으로 쓴 `dev.caskeleton`과 겹치지 않는다). 템플릿을 재사용할 +때 바꾸는 방법은 `AGENTS.md` 「템플릿 재사용 체크리스트」에 있다. ## 증거 등급 — testkit이 하나의 leaf인 이유 @@ -67,12 +71,12 @@ capability flag 뒤에 있다. `GrpcPlatformStartupValidator`가 Stable catalog 등록되면 startup을 거부한다. `grpc-spring-boot-starter`는 어떤 advanced module도 참조하지 않는다. registry의 -`allowed_dependencies`가 이를 build time에, `GrpcStableBuildInvariant`가 runtime에 강제한다. +`allowed_dependencies`와 `verifyCleanArchitectureDependencies`가 이를 build time에 강제한다. ## Optional build에 있다는 것의 의미 `grpc:*`와 `grpc-advanced:*`는 기본 `ca-skeleton` settings에 include되지 않는다. 따라서 일반 -`:app-bootstrap:build`는 이 18개 project를 configure하지 않는다. 플랫폼 자체는 +`:app-bootstrap:build`는 이 project들을 configure하지 않는다(목록은 registry의 `"build": "optional-grpc"`). 플랫폼 자체는 `./gradlew -p optional-platforms ci`로 검증하고, application runtime에 실제 채택하려면 composition root가 명시적으로 dependency를 가져오는 별도 변경이 필요하다. @@ -85,11 +89,12 @@ soak/performance baseline을 자동으로 의미하지 않는다. 지원 범위 `messaging:*`의 MSG-015(bridge 부재)를 반복하지 않는 것이 이 family의 목표다. 계약상의 경로는 ```text -application-owned port → adapter:inbound:grpc (typed service adapter) → :grpc:grpc-server SPI +application-owned port → adapter:inbound:grpc (typed service adapter) → :grpc:grpc-runtime SPI ``` -이고 `GrpcApplicationBoundaryRules`·`GrpcRawApiImportRule`·`GrpcServiceAdapter`가 그 경계를 -소유한다. 현재 `adapter:inbound:grpc`는 이 family에 의존하지 않는다 — registry의 +이고 `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와 브리지가 함께 들어간다. ## 테스트 명령 diff --git a/grpc/grpc-admin/build.gradle b/grpc/grpc-admin/build.gradle deleted file mode 100644 index fafabf0..0000000 --- a/grpc/grpc-admin/build.gradle +++ /dev/null @@ -1,10 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Operational surface: the standard health registry, the reflection exposure policy, the drain -// coordinator, and the secret-free runtime policy snapshot an administrator reads. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-server') -} diff --git a/grpc/grpc-admin/gradle.lockfile b/grpc/grpc-admin/gradle.lockfile deleted file mode 100644 index 9369e83..0000000 --- a/grpc/grpc-admin/gradle.lockfile +++ /dev/null @@ -1,91 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.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= diff --git a/grpc/grpc-client/build.gradle b/grpc/grpc-client/build.gradle deleted file mode 100644 index 3ea3d8d..0000000 --- a/grpc/grpc-client/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id 'ca.grpc-platform-module' -} - -// Client runtime: named channel profiles, channel runtime generations with drain, the typed stub -// factory that refuses to hand a raw Channel to application code, and client metadata/credentials. - -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-policy') - - api "io.grpc:grpc-api" - api "io.grpc:grpc-stub" -} diff --git a/grpc/grpc-client/gradle.lockfile b/grpc/grpc-client/gradle.lockfile deleted file mode 100644 index 9369e83..0000000 --- a/grpc/grpc-client/gradle.lockfile +++ /dev/null @@ -1,91 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.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= diff --git a/grpc/grpc-codegen/build.gradle b/grpc/grpc-codegen/build.gradle deleted file mode 100644 index f45471a..0000000 --- a/grpc/grpc-codegen/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Contract governance: Buf format/lint/breaking policy, the single codegen owner declaration, and -// the descriptor/schema-hash release artifact with its consumer-compile gate. -// -// The Buf rules are implemented here rather than shelled out to the Buf CLI (adaptation D5): the -// CLI is not present in this toolchain, and a gate that silently no-ops when a binary is missing is -// worse than one that computes the same judgement from the committed schema. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-proto-contract') -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcBreakingCategory.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcBreakingCategory.java deleted file mode 100644 index cdff661..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcBreakingCategory.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -/** - * The Buf breaking-change categories, ordered from strictest to loosest. - * - *

The Stable gate is {@link #FILE}, and the reason is the pair of properties below: only FILE - * and PACKAGE detect a change that keeps the wire format identical while breaking every generated - * consumer's compile. A team that gates on WIRE ships a field rename, watches its own integration - * tests pass, and finds out at the consumer's next build. - */ -public enum GrpcBreakingCategory { - /** Strictest: also catches file moves, package moves and Java option changes. */ - FILE(true, true), - /** Catches type and field source breaks within a package, but not a file move. */ - PACKAGE(true, false), - /** Wire plus JSON name compatibility. Source breaks pass. */ - WIRE_JSON(false, false), - /** Binary wire compatibility only. Source breaks pass. */ - WIRE(false, false); - - private final boolean detectsSourceBreak; - private final boolean detectsFileMove; - - GrpcBreakingCategory(boolean detectsSourceBreak, boolean detectsFileMove) { - this.detectsSourceBreak = detectsSourceBreak; - this.detectsFileMove = detectsFileMove; - } - - /** Whether this category fails a change that stops a generated consumer compiling. */ - public boolean detectsSourceBreak() { - return detectsSourceBreak; - } - - /** Whether this category fails a file or package relocation. */ - public boolean detectsFileMove() { - return detectsFileMove; - } - - /** The category the Stable public API is gated on. */ - public static GrpcBreakingCategory stableGate() { - return FILE; - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcBufPolicy.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcBufPolicy.java deleted file mode 100644 index 113fd66..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcBufPolicy.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import java.util.List; -import java.util.Set; - -/** - * The schema governance this repository runs, as a value the build and the tests both read. - * - *

Buf's CLI is not part of this toolchain (adaptation D5), so the four lifecycle task names - * below are the contract a CI environment fulfils and {@code GrpcProtoContractValidator} is what - * actually fails a build here. Keeping the task names in the policy rather than only in a workflow - * file means a missing stage is a test failure rather than a stage nobody noticed was gone. - */ -public record GrpcBufPolicy( - GrpcBreakingCategory breakingCategory, - boolean formatEnforced, - boolean lintEnforced, - GrpcSchemaBaseline baseline) { - - /** The lifecycle stages a compliant schema pipeline runs, in order. */ - private static final List REQUIRED_TASKS = - List.of("bufFormatCheck", "bufLint", "bufBuild", "bufBreaking"); - - /** Refuses a policy that would let a source break through. */ - public GrpcBufPolicy { - if (breakingCategory == null) { - throw new IllegalArgumentException("a Buf policy needs a breaking category"); - } - if (baseline == null) { - throw new IllegalArgumentException( - "a Buf policy needs a released baseline to compare against"); - } - if (!breakingCategory.detectsSourceBreak()) { - throw new IllegalArgumentException( - "the Stable public API may not be gated on " - + breakingCategory - + ": wire compatibility alone lets a rename through as compatible while every " - + "generated consumer stops compiling"); - } - if (!formatEnforced || !lintEnforced) { - throw new IllegalArgumentException( - "format and lint are not optional; a schema that is not linted is a schema whose style " - + "rules are whatever the last author preferred"); - } - } - - /** The Stable policy: FILE breaking, format and lint enforced. */ - public static GrpcBufPolicy stable(GrpcSchemaBaseline baseline) { - return new GrpcBufPolicy(GrpcBreakingCategory.stableGate(), true, true, baseline); - } - - /** The lifecycle task names a compliant pipeline registers. */ - public static List requiredTasks() { - return REQUIRED_TASKS; - } - - /** - * The task names missing from {@code registeredTasks}. - * - * @return an empty set when the pipeline is complete - */ - public static Set missingTasks(Set registeredTasks) { - if (registeredTasks == null) { - throw new IllegalArgumentException("the registered task set must not be null"); - } - return REQUIRED_TASKS.stream() - .filter(task -> !registeredTasks.contains(task)) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - } - - /** Whether a candidate schema hash may be released without a breaking review. */ - public boolean unchangedFromBaseline(String candidateSchemaHash) { - return baseline.matches(candidateSchemaHash); - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcCodegenManifest.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcCodegenManifest.java deleted file mode 100644 index 38fb194..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcCodegenManifest.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -/** - * Who generates Java from the schema, with what versions, into where. - * - *

One owner, named. Two generators for one schema is the state in which a type exists twice with - * different options and the classpath decides which one a consumer gets; refusing a second owner is - * cheaper than diagnosing that. - * - *

Both version sources are required to be the managed BOM rather than a literal. A pinned - * protobuf version beside a BOM-managed gRPC version is how the runtime and the generator drift - * into a combination nobody tested, and the symptom is a {@code NoSuchMethodError} in generated - * code. - */ -public record GrpcCodegenManifest( - String codegenOwner, - String protobufVersionSource, - String grpcJavaVersionSource, - GrpcCodegenOutput output, - GrpcGeneratedPackagePolicy packagePolicy) { - - /** The only accepted version source: whatever the build's managed platform resolves. */ - public static final String MANAGED_VERSION_SOURCE = "managed-platform"; - - /** Refuses a second owner, a literal version, or overlapping package namespaces. */ - public GrpcCodegenManifest { - if (codegenOwner == null || codegenOwner.isBlank()) { - throw new IllegalArgumentException("code generation needs exactly one named owner"); - } - if (output == null || packagePolicy == null) { - throw new IllegalArgumentException("a codegen manifest needs an output and a package policy"); - } - requireManagedVersion(protobufVersionSource, "protobuf"); - requireManagedVersion(grpcJavaVersionSource, "grpc-java"); - packagePolicy.requireDisjoint(); - } - - private static void requireManagedVersion(String source, String what) { - if (!MANAGED_VERSION_SOURCE.equals(source)) { - throw new IllegalArgumentException( - what - + " version must come from the managed platform, not from a literal declaration; got '" - + source - + "'. A pinned generator beside a managed runtime is a combination nobody tested."); - } - } - - /** - * This repository's manifest. - * - *

The owner is the Gradle protobuf plugin. It does not run in this build yet — adaptation D6 - * records why, and this manifest is what a future decision to turn it on has to satisfy rather - * than replace. - */ - public static GrpcCodegenManifest caSkeleton() { - return new GrpcCodegenManifest( - "gradle-protobuf-plugin", - MANAGED_VERSION_SOURCE, - MANAGED_VERSION_SOURCE, - GrpcCodegenOutput.standard(), - new GrpcGeneratedPackagePolicy( - java.util.Set.of("dev.caskeleton"), - java.util.Set.of("hyeonworks.grpc.common.v1.generated"))); - } - - /** - * Fails when a second generator claims the same schema. - * - * @throws IllegalStateException when {@code otherOwner} is not this manifest's owner - */ - public void requireSoleOwner(String otherOwner) { - if (!codegenOwner.equals(otherOwner)) { - throw new IllegalStateException( - "Java code generation for this schema is owned by '" - + codegenOwner - + "'; '" - + otherOwner - + "' may not also generate it"); - } - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcCodegenOutput.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcCodegenOutput.java deleted file mode 100644 index 719efdd..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcCodegenOutput.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -/** - * Where generated artifacts land. - * - *

Everything here is required to be inside a build directory. A generator that writes into a - * source tree produces files that get committed, then edited, then silently reverted by the next - * regeneration — and the diff that reverts them looks like the generator working correctly. - */ -public record GrpcCodegenOutput( - String javaOutputDirectory, - String grpcJavaOutputDirectory, - String descriptorSetPath, - boolean includeSourceInfo) { - - private static final String BUILD_ROOT = "build/"; - - /** Requires every path to be build-directory relative. */ - public GrpcCodegenOutput { - requireBuildRelative(javaOutputDirectory, "java output directory"); - requireBuildRelative(grpcJavaOutputDirectory, "grpc-java output directory"); - requireBuildRelative(descriptorSetPath, "descriptor set path"); - if (!descriptorSetPath.endsWith(".desc") && !descriptorSetPath.endsWith(".binpb")) { - throw new IllegalArgumentException( - "a descriptor set is a serialized FileDescriptorSet; expected a .desc or .binpb path, got '" - + descriptorSetPath - + "'"); - } - } - - private static void requireBuildRelative(String path, String what) { - if (path == null || path.isBlank()) { - throw new IllegalArgumentException(what + " must not be blank"); - } - if (path.startsWith("/") || path.contains("..")) { - throw new IllegalArgumentException( - what + " must be a project-relative path without '..'; got '" + path + "'"); - } - if (!path.startsWith(BUILD_ROOT)) { - throw new IllegalArgumentException( - what - + " must be under '" - + BUILD_ROOT - + "'; generated sources in a source tree get committed and then edited. Got '" - + path - + "'"); - } - } - - /** This repository's layout. */ - public static GrpcCodegenOutput standard() { - return new GrpcCodegenOutput( - "build/generated/source/proto/main/java", - "build/generated/source/proto/main/grpc", - "build/generated/descriptor/stable-schema.desc", - true); - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcConsumerFixture.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcConsumerFixture.java deleted file mode 100644 index 189cbfe..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcConsumerFixture.java +++ /dev/null @@ -1,158 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -/** - * A previously released consumer, described by exactly what it compiles against. - * - *

This is the check a wire-compatibility gate cannot make. A field rename, a service move to a - * new package, or a change to {@code java_package} keeps every serialized message valid and stops - * every generated client compiling — and the only way to notice before the consumer does is to keep - * a record of what the consumer names and compare a candidate schema against it. - */ -public record GrpcConsumerFixture( - String name, - String schemaVersion, - Set requiredServicePaths, - Set requiredMethodPaths, - Set requiredJavaPackages) { - - /** What kind of source break a consumer hit. Reported separately, never merged into one count. */ - public enum BreakKind { - /** A service the consumer names is gone or moved. */ - SERVICE_PATH, - /** A method the consumer calls is gone or renamed. */ - METHOD_PATH, - /** The Java package the consumer imports from moved. */ - JAVA_PACKAGE - } - - /** One thing a consumer needs that a candidate schema no longer provides. */ - public record SourceBreak(BreakKind kind, String missing) { - /** Requires both halves. */ - public SourceBreak { - if (kind == null || missing == null || missing.isBlank()) { - throw new IllegalArgumentException("a source break names its kind and what went missing"); - } - } - } - - /** Copies every requirement set. */ - public GrpcConsumerFixture { - if (name == null || name.isBlank()) { - throw new IllegalArgumentException("a consumer fixture needs a name"); - } - if (schemaVersion == null || schemaVersion.isBlank()) { - throw new IllegalArgumentException( - "a consumer fixture names the schema version it was built against"); - } - if (requiredServicePaths == null - || requiredMethodPaths == null - || requiredJavaPackages == null) { - throw new IllegalArgumentException("a consumer fixture states all three requirement sets"); - } - requiredServicePaths = Set.copyOf(requiredServicePaths); - requiredMethodPaths = Set.copyOf(requiredMethodPaths); - requiredJavaPackages = Set.copyOf(requiredJavaPackages); - } - - /** - * Derives a fixture from a released consumer's own source. - * - *

Read from the consumer rather than declared beside it, because a hand-written requirement - * list is a second copy of what the client already says and the copy is the one that stops being - * updated. Three rules, all mechanical: - * - *

    - *
  • a generated Java package is any package a {@code fixture} class imports from; - *
  • a service is a {@code Grpc} import, mapped back to {@code .} with - * the generated-package suffix removed; - *
  • a method is a {@code stub.(} call, mapped to {@code /}. - *
- * - *

It is an approximation of compiling the fixture, which is what the plan asks for and what - * ADR-GRPC-002 records this repository cannot do yet. It is a useful approximation because it - * fails on exactly the changes a compile would fail on: a renamed method, a moved service, a - * relocated Java package. - * - * @param generatedPackageSuffix the segment appended to a proto package for generated code, e.g. - * {@code generated}; removed to recover the schema's own service path - */ - public static GrpcConsumerFixture fromJavaSource( - String name, String schemaVersion, String javaSource, String generatedPackageSuffix) { - if (javaSource == null || javaSource.isBlank()) { - throw new IllegalArgumentException("a consumer fixture needs its source text"); - } - if (generatedPackageSuffix == null || generatedPackageSuffix.isBlank()) { - throw new IllegalArgumentException("the generated package suffix is required"); - } - - java.util.Set javaPackages = new LinkedHashSet<>(); - java.util.Set servicePaths = new LinkedHashSet<>(); - java.util.regex.Matcher imports = - java.util.regex.Pattern.compile( - "^\\s*import\\s+([\\w.]+)\\.(\\w+);", java.util.regex.Pattern.MULTILINE) - .matcher(javaSource); - while (imports.find()) { - String importedPackage = imports.group(1); - String importedType = imports.group(2); - if (!importedPackage.endsWith("." + generatedPackageSuffix)) { - continue; - } - javaPackages.add(importedPackage); - if (importedType.endsWith("Grpc")) { - String protoPackage = - importedPackage.substring( - 0, importedPackage.length() - generatedPackageSuffix.length() - 1); - servicePaths.add( - protoPackage - + "." - + importedType.substring(0, importedType.length() - "Grpc".length())); - } - } - - java.util.Set methodPaths = new LinkedHashSet<>(); - java.util.regex.Matcher calls = - java.util.regex.Pattern.compile("\\bstub\\.(\\w+)\\s*\\(").matcher(javaSource); - while (calls.find()) { - String method = calls.group(1); - String upperCamel = Character.toUpperCase(method.charAt(0)) + method.substring(1); - servicePaths.forEach(service -> methodPaths.add(service + "/" + upperCamel)); - } - - if (servicePaths.isEmpty() || methodPaths.isEmpty()) { - throw new IllegalArgumentException( - "no service or method could be derived from '" - + name - + "'; a fixture that requires nothing cannot detect a break"); - } - return new GrpcConsumerFixture(name, schemaVersion, servicePaths, methodPaths, javaPackages); - } - - /** - * What this consumer would fail to compile against {@code candidate}. - * - * @return an empty list when the consumer still compiles - */ - public List breaksAgainst(GrpcDescriptorArtifact candidate) { - if (candidate == null) { - throw new IllegalArgumentException("a compatibility check needs a candidate artifact"); - } - List breaks = new ArrayList<>(); - collect(breaks, BreakKind.SERVICE_PATH, requiredServicePaths, candidate.servicePaths()); - collect(breaks, BreakKind.METHOD_PATH, requiredMethodPaths, candidate.methodPaths()); - collect( - breaks, BreakKind.JAVA_PACKAGE, requiredJavaPackages, candidate.generatedJavaPackages()); - return List.copyOf(breaks); - } - - private static void collect( - List breaks, BreakKind kind, Set required, Set available) { - Set missing = new LinkedHashSet<>(required); - missing.removeAll(available); - missing.stream().sorted().forEach(entry -> breaks.add(new SourceBreak(kind, entry))); - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcDescriptorArtifact.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcDescriptorArtifact.java deleted file mode 100644 index c6a1c39..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcDescriptorArtifact.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import java.util.Set; - -/** - * One immutable release of the schema: what it contains, and the hashes that prove which bytes it - * was built from. - * - *

Service and method paths are carried explicitly, not derived on demand, because they are what - * a consumer compatibility check compares. A descriptor that only carries a digest can say - * "something changed" and nothing else, which is the answer least useful to the person who has to - * decide whether to release. - */ -public record GrpcDescriptorArtifact( - String schemaVersion, - String schemaHash, - String descriptorSetDigest, - String bufImageDigest, - String policyVersion, - Set servicePaths, - Set methodPaths, - Set generatedJavaPackages) { - - /** Requires an immutable version, three digests and a non-empty surface. */ - public GrpcDescriptorArtifact { - if (schemaVersion == null || schemaVersion.isBlank() || schemaVersion.endsWith("-SNAPSHOT")) { - throw new IllegalArgumentException( - "a schema artifact publishes an immutable version; got '" + schemaVersion + "'"); - } - requireDigest(schemaHash, "schema hash"); - requireDigest(descriptorSetDigest, "descriptor set digest"); - requireDigest(bufImageDigest, "buf image digest"); - if (policyVersion == null || policyVersion.isBlank()) { - throw new IllegalArgumentException( - "a schema artifact records the policy version it was judged under"); - } - if (servicePaths == null || methodPaths == null || generatedJavaPackages == null) { - throw new IllegalArgumentException( - "a schema artifact carries its service, method and package surface"); - } - if (methodPaths.isEmpty()) { - throw new IllegalArgumentException("a schema artifact with no methods describes nothing"); - } - servicePaths = Set.copyOf(servicePaths); - methodPaths = Set.copyOf(methodPaths); - generatedJavaPackages = Set.copyOf(generatedJavaPackages); - } - - private static void requireDigest(String digest, String what) { - if (digest == null || !digest.startsWith("sha256:") || digest.length() < 15) { - throw new IllegalArgumentException(what + " must be 'sha256:'; got '" + digest + "'"); - } - } - - /** Whether this artifact is byte-identical to {@code baseline}. */ - public boolean unchangedFrom(GrpcSchemaBaseline baseline) { - return baseline.matches(schemaHash); - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcGeneratedPackagePolicy.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcGeneratedPackagePolicy.java deleted file mode 100644 index fd74568..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcGeneratedPackagePolicy.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * Keeps generated Java packages and hand-written ones apart. - * - *

An overlap is not a style problem. Generated code is deleted and rewritten on every build, so - * a hand-written class that shares its package is one clean build away from being either - * overwritten or, more often, from making the generator's output unbuildable in a way that reads as - * a compiler bug. Splitting the namespaces makes the ownership of every file legible from its - * package alone. - */ -public record GrpcGeneratedPackagePolicy( - Set handWrittenPackages, Set generatedPackages) { - - /** Copies both sets. */ - public GrpcGeneratedPackagePolicy { - if (handWrittenPackages == null || generatedPackages == null) { - throw new IllegalArgumentException("both package sets must be present"); - } - if (generatedPackages.isEmpty()) { - throw new IllegalArgumentException("a codegen policy names at least one generated package"); - } - handWrittenPackages = Set.copyOf(handWrittenPackages); - generatedPackages = Set.copyOf(generatedPackages); - } - - /** - * Every overlap between the two namespaces, described. - * - * @return an empty list when the namespaces are disjoint - */ - public List overlaps() { - List overlaps = new ArrayList<>(); - for (String generated : generatedPackages) { - for (String handWritten : handWrittenPackages) { - if (generated.equals(handWritten) - || generated.startsWith(handWritten + ".") - || handWritten.startsWith(generated + ".")) { - overlaps.add( - "generated package '" - + generated - + "' overlaps hand-written package '" - + handWritten - + "'"); - } - } - } - overlaps.sort(java.util.Comparator.naturalOrder()); - return List.copyOf(overlaps); - } - - /** - * Fails when the namespaces overlap. - * - * @throws IllegalStateException naming every overlap - */ - public void requireDisjoint() { - List overlaps = overlaps(); - if (!overlaps.isEmpty()) { - throw new IllegalStateException( - "generated and hand-written Java packages must be disjoint: " + overlaps); - } - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcSchemaArtifactPublisher.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcSchemaArtifactPublisher.java deleted file mode 100644 index 225894c..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcSchemaArtifactPublisher.java +++ /dev/null @@ -1,113 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Decides whether a candidate schema may be published, and refuses to let a released version change - * underneath its consumers. - * - *

Two rules, and the second is the one that gets skipped in a hurry: a consumer fixture that no - * longer compiles blocks the release. Publishing anyway and telling the consumers is not the same - * thing — by then the artifact exists, somebody has resolved it, and the fix is a new version - * rather than a decision not to make the change. - */ -public final class GrpcSchemaArtifactPublisher { - - private final GrpcBufPolicy policy; - private final Map publishedHashesByVersion = new LinkedHashMap<>(); - - /** Binds a publisher to the governance policy it enforces. */ - public GrpcSchemaArtifactPublisher(GrpcBufPolicy policy) { - if (policy == null) { - throw new IllegalArgumentException("a publisher needs a Buf policy"); - } - this.policy = policy; - } - - /** Whether a candidate may be published, and if not, why not. */ - public record PublishDecision(boolean allowed, List blockers) { - /** Copies the blocker list. */ - public PublishDecision { - if (blockers == null) { - throw new IllegalArgumentException( - "a publish decision lists its blockers, even when empty"); - } - blockers = List.copyOf(blockers); - if (allowed && !blockers.isEmpty()) { - throw new IllegalArgumentException("an allowed publish has no blockers"); - } - if (!allowed && blockers.isEmpty()) { - throw new IllegalArgumentException("a refused publish says why"); - } - } - } - - /** - * Evaluates a candidate against the policy and every consumer fixture. - * - * @param fixtures the previously released consumers this schema must keep compiling - */ - public PublishDecision evaluate( - GrpcDescriptorArtifact candidate, List fixtures) { - if (candidate == null || fixtures == null) { - throw new IllegalArgumentException("evaluation needs a candidate and a fixture list"); - } - List blockers = new ArrayList<>(); - - String alreadyPublished = publishedHashesByVersion.get(candidate.schemaVersion()); - if (alreadyPublished != null && !alreadyPublished.equals(candidate.schemaHash())) { - blockers.add( - "version '" - + candidate.schemaVersion() - + "' is already published with a different schema hash; a released schema version is " - + "immutable"); - } - if (!policy.breakingCategory().detectsSourceBreak()) { - blockers.add("the active breaking category does not detect source breaks"); - } - for (GrpcConsumerFixture fixture : fixtures) { - for (GrpcConsumerFixture.SourceBreak sourceBreak : fixture.breaksAgainst(candidate)) { - blockers.add( - "consumer '" - + fixture.name() - + "' (" - + fixture.schemaVersion() - + ") loses " - + sourceBreak.kind() - + " '" - + sourceBreak.missing() - + "'"); - } - } - return new PublishDecision(blockers.isEmpty(), blockers); - } - - /** - * Records a successful publish. - * - * @throws IllegalStateException when the decision refused it - */ - public void publish(GrpcDescriptorArtifact candidate, PublishDecision decision) { - if (decision == null || !decision.allowed()) { - throw new IllegalStateException( - "refusing to publish '" - + (candidate == null ? "null" : candidate.schemaVersion()) - + "': " - + (decision == null ? "no decision" : decision.blockers())); - } - publishedHashesByVersion.put(candidate.schemaVersion(), candidate.schemaHash()); - } - - /** The hash published for {@code version}, or null when nothing was. */ - public String publishedHash(String version) { - return publishedHashesByVersion.get(version); - } - - /** The governance policy in force. */ - public GrpcBufPolicy policy() { - return policy; - } -} diff --git a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcSchemaBaseline.java b/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcSchemaBaseline.java deleted file mode 100644 index c0468ba..0000000 --- a/grpc/grpc-codegen/src/main/java/dev/caskeleton/grpc/codegen/GrpcSchemaBaseline.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import java.time.Instant; - -/** - * The released schema a breaking check compares against. - * - *

Pinned to a released artifact rather than to a branch, and that is the whole point. Comparing - * against the previous commit answers "did this commit break anything", which is not the question: - * a breaking change introduced two commits ago and refined since then passes every commit-to-commit - * check while being broken against everything that has actually been deployed. - */ -public record GrpcSchemaBaseline(String version, String schemaHash, Instant releasedAt) { - - /** Requires an immutable version, a hash and a release moment. */ - public GrpcSchemaBaseline { - if (version == null || version.isBlank()) { - throw new IllegalArgumentException("a schema baseline needs a released version"); - } - if (version.endsWith("-SNAPSHOT")) { - throw new IllegalArgumentException( - "a breaking baseline must be an immutable release, not '" + version + "'"); - } - if (schemaHash == null || !schemaHash.startsWith("sha256:") || schemaHash.length() < 15) { - throw new IllegalArgumentException( - "a schema baseline needs a 'sha256:' hash; got '" + schemaHash + "'"); - } - if (releasedAt == null) { - throw new IllegalArgumentException("a schema baseline needs a release timestamp"); - } - } - - /** Whether {@code candidateHash} is byte-identical to this baseline. */ - public boolean matches(String candidateHash) { - return schemaHash.equals(candidateHash); - } -} diff --git a/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcBufPolicyTest.java b/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcBufPolicyTest.java deleted file mode 100644 index efb2756..0000000 --- a/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcBufPolicyTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcBufPolicyTest { - - private static final GrpcSchemaBaseline BASELINE = - new GrpcSchemaBaseline( - "1.4.0", - "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0", - Instant.parse("2026-08-01T00:00:00Z")); - - @Test - @DisplayName("the Stable public API is gated on the FILE breaking category") - void stablePublicApiUsesTheFileCategory() { - GrpcBufPolicy policy = GrpcBufPolicy.stable(BASELINE); - - assertThat(policy.breakingCategory()).isEqualTo(GrpcBreakingCategory.FILE); - assertThat(GrpcBreakingCategory.stableGate()).isEqualTo(GrpcBreakingCategory.FILE); - assertThat(policy.breakingCategory().detectsSourceBreak()).isTrue(); - assertThat(policy.breakingCategory().detectsFileMove()).isTrue(); - } - - @Test - @DisplayName("wire-only compatibility may not gate the Stable public API") - void wireOnlyCompatibilityIsRefused() { - assertThatThrownBy(() -> new GrpcBufPolicy(GrpcBreakingCategory.WIRE, true, true, BASELINE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("stops compiling"); - assertThatThrownBy( - () -> new GrpcBufPolicy(GrpcBreakingCategory.WIRE_JSON, true, true, BASELINE)) - .isInstanceOf(IllegalArgumentException.class); - assertThat(GrpcBreakingCategory.WIRE.detectsSourceBreak()).isFalse(); - assertThat(GrpcBreakingCategory.PACKAGE.detectsFileMove()).isFalse(); - } - - @Test - @DisplayName("format and lint are not optional") - void formatAndLintAreNotOptional() { - assertThatThrownBy(() -> new GrpcBufPolicy(GrpcBreakingCategory.FILE, false, true, BASELINE)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GrpcBufPolicy(GrpcBreakingCategory.FILE, true, false, BASELINE)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the four lifecycle stages are named, and a missing one is reported") - void lifecycleStagesAreNamedAndChecked() { - assertThat(GrpcBufPolicy.requiredTasks()) - .containsExactly("bufFormatCheck", "bufLint", "bufBuild", "bufBreaking"); - assertThat(GrpcBufPolicy.missingTasks(Set.of("bufFormatCheck", "bufLint", "bufBuild"))) - .containsExactly("bufBreaking"); - assertThat(GrpcBufPolicy.missingTasks(Set.copyOf(GrpcBufPolicy.requiredTasks()))).isEmpty(); - } - - @Test - @DisplayName("the breaking baseline is a released version, never a snapshot") - void baselineIsAnImmutableRelease() { - assertThatThrownBy( - () -> - new GrpcSchemaBaseline( - "1.5.0-SNAPSHOT", - "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0", - Instant.parse("2026-08-01T00:00:00Z"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("immutable release"); - assertThatThrownBy( - () -> - new GrpcSchemaBaseline( - "1.5.0", "not-a-digest", Instant.parse("2026-08-01T00:00:00Z"))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("an unchanged schema hash needs no breaking review") - void unchangedSchemaNeedsNoBreakingReview() { - GrpcBufPolicy policy = GrpcBufPolicy.stable(BASELINE); - - assertThat(policy.unchangedFromBaseline(BASELINE.schemaHash())).isTrue(); - assertThat(policy.unchangedFromBaseline("sha256:ffffffffffffffffffffffffffffffff")).isFalse(); - } -} diff --git a/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcCodegenManifestTest.java b/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcCodegenManifestTest.java deleted file mode 100644 index c579df3..0000000 --- a/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcCodegenManifestTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -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 GrpcCodegenManifestTest { - - @Test - @DisplayName("Java code generation has exactly one owner, and a second is refused") - void codeGenerationHasOneOwner() { - GrpcCodegenManifest manifest = GrpcCodegenManifest.caSkeleton(); - - manifest.requireSoleOwner("gradle-protobuf-plugin"); - assertThatThrownBy(() -> manifest.requireSoleOwner("hand-rolled-protoc-exec")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("hand-rolled-protoc-exec"); - } - - @Test - @DisplayName("generator versions come from the managed platform, never from a literal") - void generatorVersionsComeFromTheManagedPlatform() { - assertThatThrownBy( - () -> - new GrpcCodegenManifest( - "gradle-protobuf-plugin", - "3.25.5", - GrpcCodegenManifest.MANAGED_VERSION_SOURCE, - GrpcCodegenOutput.standard(), - new GrpcGeneratedPackagePolicy( - Set.of("dev.caskeleton"), Set.of("hyeonworks.grpc.common.v1.generated")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("protobuf version must come from the managed platform"); - } - - @Test - @DisplayName("generated sources land under build/, never in a source tree") - void generatedSourcesLandUnderBuild() { - assertThatThrownBy( - () -> new GrpcCodegenOutput("src/main/java", "build/g", "build/x.desc", true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("must be under 'build/'"); - assertThatThrownBy(() -> new GrpcCodegenOutput("build/a", "build/b", "build/schema.txt", true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("FileDescriptorSet"); - assertThat(GrpcCodegenOutput.standard().includeSourceInfo()).isTrue(); - } - - @Test - @DisplayName("a generated package inside a hand-written one fails the manifest") - void generatedAndHandWrittenPackagesMustBeDisjoint() { - GrpcGeneratedPackagePolicy overlapping = - new GrpcGeneratedPackagePolicy( - Set.of("dev.caskeleton"), Set.of("dev.caskeleton.grpc.generated")); - - assertThat(overlapping.overlaps()).hasSize(1); - assertThatThrownBy(overlapping::requireDisjoint) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("dev.caskeleton.grpc.generated"); - assertThat( - new GrpcGeneratedPackagePolicy( - Set.of("dev.caskeleton"), Set.of("hyeonworks.grpc.common.v1.generated")) - .overlaps()) - .isEmpty(); - } - - @Test - @DisplayName("an overlap is caught in both directions") - void overlapIsSymmetric() { - GrpcGeneratedPackagePolicy generatedIsAnAncestor = - new GrpcGeneratedPackagePolicy(Set.of("hyeonworks.grpc.hand"), Set.of("hyeonworks.grpc")); - - assertThat(generatedIsAnAncestor.overlaps()).hasSize(1); - } -} diff --git a/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcDescriptorArtifactTest.java b/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcDescriptorArtifactTest.java deleted file mode 100644 index fb25a9a..0000000 --- a/grpc/grpc-codegen/src/test/java/dev/caskeleton/grpc/codegen/GrpcDescriptorArtifactTest.java +++ /dev/null @@ -1,248 +0,0 @@ -package dev.caskeleton.grpc.codegen; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.List; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcDescriptorArtifactTest { - - private static final String DIGEST_A = - "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; - private static final String DIGEST_B = - "sha256:1122334455667788990011223344556677889900112233445566778899001122"; - - private static final GrpcSchemaBaseline BASELINE = - new GrpcSchemaBaseline("1.4.0", DIGEST_A, Instant.parse("2026-08-01T00:00:00Z")); - - private static GrpcDescriptorArtifact artifact( - String version, String hash, Set methods, Set javaPackages) { - return new GrpcDescriptorArtifact( - version, - hash, - DIGEST_A, - DIGEST_B, - "grpc-stable-policy-1", - Set.of("hyeonworks.document.v1.DocumentService"), - methods, - javaPackages); - } - - private static final Set METHODS = - Set.of( - "hyeonworks.document.v1.DocumentService/GetDocument", - "hyeonworks.document.v1.DocumentService/CreateDocument"); - private static final Set PACKAGES = Set.of("hyeonworks.document.v1.generated"); - - private static String resource(String path) { - try (java.io.InputStream stream = - GrpcDescriptorArtifactTest.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); - } - } - - @Test - @DisplayName("a schema artifact publishes an immutable version and three digests") - void artifactCarriesAnImmutableVersionAndDigests() { - GrpcDescriptorArtifact candidate = artifact("1.5.0", DIGEST_B, METHODS, PACKAGES); - - assertThat(candidate.schemaVersion()).isEqualTo("1.5.0"); - assertThat(candidate.unchangedFrom(BASELINE)).isFalse(); - assertThat(artifact("1.4.0", DIGEST_A, METHODS, PACKAGES).unchangedFrom(BASELINE)).isTrue(); - assertThatThrownBy(() -> artifact("1.5.0-SNAPSHOT", DIGEST_B, METHODS, PACKAGES)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("immutable version"); - assertThatThrownBy(() -> artifact("1.5.0", "nope", METHODS, PACKAGES)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("service, method and Java package breaks are reported separately") - void sourceBreaksAreReportedByKind() { - GrpcConsumerFixture consumer = - new GrpcConsumerFixture( - "document-client-v1", - "1.4.0", - Set.of("hyeonworks.document.v1.DocumentService"), - METHODS, - PACKAGES); - GrpcDescriptorArtifact renamedEverything = - new GrpcDescriptorArtifact( - "1.5.0", - DIGEST_B, - DIGEST_A, - DIGEST_B, - "grpc-stable-policy-1", - Set.of("hyeonworks.document.v2.DocumentService"), - Set.of("hyeonworks.document.v2.DocumentService/GetDocument"), - Set.of("hyeonworks.document.v2.generated")); - - List breaks = consumer.breaksAgainst(renamedEverything); - - assertThat(breaks) - .extracting(GrpcConsumerFixture.SourceBreak::kind) - .containsExactlyInAnyOrder( - GrpcConsumerFixture.BreakKind.SERVICE_PATH, - GrpcConsumerFixture.BreakKind.METHOD_PATH, - GrpcConsumerFixture.BreakKind.METHOD_PATH, - GrpcConsumerFixture.BreakKind.JAVA_PACKAGE); - } - - @Test - @DisplayName("a consumer that still compiles reports no break") - void compatibleSchemaBreaksNothing() { - GrpcConsumerFixture consumer = - new GrpcConsumerFixture( - "document-client-v1", - "1.4.0", - Set.of("hyeonworks.document.v1.DocumentService"), - METHODS, - PACKAGES); - Set widened = - Set.of( - "hyeonworks.document.v1.DocumentService/GetDocument", - "hyeonworks.document.v1.DocumentService/CreateDocument", - "hyeonworks.document.v1.DocumentService/ArchiveDocument"); - - assertThat(consumer.breaksAgainst(artifact("1.5.0", DIGEST_B, widened, PACKAGES))).isEmpty(); - } - - @Test - @DisplayName("the committed v1 consumer fixture states its own requirements") - void theCommittedFixtureStatesItsOwnRequirements() { - GrpcConsumerFixture derived = - GrpcConsumerFixture.fromJavaSource( - "document-client-v1", - "1.4.0", - resource("consumer-fixtures/v1/src/main/java/fixture/DocumentClientFixture.java"), - "generated"); - - assertThat(derived.requiredServicePaths()) - .containsExactly("hyeonworks.document.v1.DocumentService"); - assertThat(derived.requiredMethodPaths()) - .containsExactlyInAnyOrder( - "hyeonworks.document.v1.DocumentService/GetDocument", - "hyeonworks.document.v1.DocumentService/CreateDocument"); - assertThat(derived.requiredJavaPackages()).containsExactly("hyeonworks.document.v1.generated"); - } - - @Test - @DisplayName("a schema that renames a method the committed fixture calls blocks the release") - void renamingAMethodTheFixtureCallsBlocksTheRelease() { - GrpcConsumerFixture derived = - GrpcConsumerFixture.fromJavaSource( - "document-client-v1", - "1.4.0", - resource("consumer-fixtures/v1/src/main/java/fixture/DocumentClientFixture.java"), - "generated"); - GrpcDescriptorArtifact renamed = - new GrpcDescriptorArtifact( - "1.5.0", - DIGEST_B, - DIGEST_A, - DIGEST_B, - "grpc-stable-policy-1", - Set.of("hyeonworks.document.v1.DocumentService"), - Set.of( - "hyeonworks.document.v1.DocumentService/GetDocument", - "hyeonworks.document.v1.DocumentService/CreateDocumentV2"), - Set.of("hyeonworks.document.v1.generated")); - - GrpcSchemaArtifactPublisher publisher = - new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE)); - - assertThat(publisher.evaluate(renamed, List.of(derived)).blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("CreateDocument")); - } - - @Test - @DisplayName("a fixture that requires nothing is refused rather than passing every schema") - void aFixtureThatRequiresNothingIsRefused() { - assertThatThrownBy( - () -> - GrpcConsumerFixture.fromJavaSource( - "empty-client", "1.4.0", "package fixture;\n\nclass Empty {}\n", "generated")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cannot detect a break"); - } - - @Test - @DisplayName("the fixture's own build file pins the schema version it was built against") - void theFixturePinsItsSchemaVersion() { - assertThat(resource("consumer-fixtures/v1/build.gradle.kts")) - .contains("grpc-schema-artifact:1.4.0") - .contains("floats to the latest version"); - } - - @Test - @DisplayName("a consumer fixture failure blocks the release") - void consumerFixtureFailureBlocksTheRelease() { - GrpcSchemaArtifactPublisher publisher = - new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE)); - GrpcConsumerFixture consumer = - new GrpcConsumerFixture( - "document-client-v1", - "1.4.0", - Set.of("hyeonworks.document.v1.DocumentService"), - METHODS, - PACKAGES); - GrpcDescriptorArtifact dropsAMethod = - artifact( - "1.5.0", - DIGEST_B, - Set.of("hyeonworks.document.v1.DocumentService/GetDocument"), - PACKAGES); - - GrpcSchemaArtifactPublisher.PublishDecision decision = - publisher.evaluate(dropsAMethod, List.of(consumer)); - - assertThat(decision.allowed()).isFalse(); - assertThat(decision.blockers()) - .anySatisfy( - blocker -> - assertThat(blocker).contains("document-client-v1").contains("CreateDocument")); - assertThatThrownBy(() -> publisher.publish(dropsAMethod, decision)) - .isInstanceOf(IllegalStateException.class); - } - - @Test - @DisplayName("a released version may not be republished with different bytes") - void releasedVersionsAreImmutable() { - GrpcSchemaArtifactPublisher publisher = - new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE)); - GrpcDescriptorArtifact first = artifact("1.5.0", DIGEST_B, METHODS, PACKAGES); - - GrpcSchemaArtifactPublisher.PublishDecision allowed = publisher.evaluate(first, List.of()); - assertThat(allowed.allowed()).isTrue(); - publisher.publish(first, allowed); - assertThat(publisher.publishedHash("1.5.0")).isEqualTo(DIGEST_B); - - GrpcDescriptorArtifact sameVersionDifferentBytes = - artifact("1.5.0", DIGEST_A, METHODS, PACKAGES); - - assertThat(publisher.evaluate(sameVersionDifferentBytes, List.of()).blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("immutable")); - } - - @Test - @DisplayName("republishing identical bytes under the same version is allowed") - void identicalRepublishIsAllowed() { - GrpcSchemaArtifactPublisher publisher = - new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE)); - GrpcDescriptorArtifact artifact = artifact("1.5.0", DIGEST_B, METHODS, PACKAGES); - - publisher.publish(artifact, publisher.evaluate(artifact, List.of())); - - assertThat(publisher.evaluate(artifact, List.of()).allowed()).isTrue(); - assertThat(publisher.policy().breakingCategory()).isEqualTo(GrpcBreakingCategory.FILE); - } -} diff --git a/grpc/grpc-codegen/src/test/resources/consumer-fixtures/v1/build.gradle.kts b/grpc/grpc-codegen/src/test/resources/consumer-fixtures/v1/build.gradle.kts deleted file mode 100644 index 3351027..0000000 --- a/grpc/grpc-codegen/src/test/resources/consumer-fixtures/v1/build.gradle.kts +++ /dev/null @@ -1,17 +0,0 @@ -// The v1 consumer fixture's own build file, kept as a test resource. -// -// It is not part of this repository's Gradle build. Its purpose is to record what a released -// consumer actually depended on — the schema artifact version and nothing else — so that when -// protoc generation is switched on (ADR-GRPC-002) this directory can be compiled as-is against a -// candidate schema, which is the check GrpcConsumerFixture currently approximates from source text. -plugins { - `java-library` -} - -dependencies { - // The released schema artifact, pinned. A fixture that floats to the latest version cannot - // detect a break, because it is always built against the schema it is meant to be testing. - implementation("dev.caskeleton.grpc:grpc-schema-artifact:1.4.0") - implementation("io.grpc:grpc-stub") - implementation("io.grpc:grpc-protobuf") -} diff --git a/grpc/grpc-codegen/src/test/resources/consumer-fixtures/v1/src/main/java/fixture/DocumentClientFixture.java b/grpc/grpc-codegen/src/test/resources/consumer-fixtures/v1/src/main/java/fixture/DocumentClientFixture.java deleted file mode 100644 index 45394dc..0000000 --- a/grpc/grpc-codegen/src/test/resources/consumer-fixtures/v1/src/main/java/fixture/DocumentClientFixture.java +++ /dev/null @@ -1,33 +0,0 @@ -package fixture; - -import hyeonworks.document.v1.generated.CreateDocumentRequest; -import hyeonworks.document.v1.generated.DocumentServiceGrpc; -import hyeonworks.document.v1.generated.GetDocumentRequest; - -/** - * A previously released consumer, kept as a fixture rather than as a dependency. - * - *

This file is a test resource, not a compiled source. It records exactly what the v1 client - * named — the generated package it imported from, the service class it referenced and the methods it - * called — so a candidate schema can be checked against a real client's surface instead of against a - * requirement list somebody typed by hand and will forget to update. - * - *

{@code GrpcConsumerFixture.fromJavaSource} derives those three sets from this text. Adding a - * call here widens what a release must keep; that is the intent. - */ -public final class DocumentClientFixture { - - private final DocumentServiceGrpc.DocumentServiceBlockingStub stub; - - public DocumentClientFixture(DocumentServiceGrpc.DocumentServiceBlockingStub stub) { - this.stub = stub; - } - - public String read(String documentId) { - return stub.getDocument(GetDocumentRequest.newBuilder().setId(documentId).build()).getTitle(); - } - - public String create(String title) { - return stub.createDocument(CreateDocumentRequest.newBuilder().setTitle(title).build()).getId(); - } -} diff --git a/grpc/grpc-contract/buf.yaml b/grpc/grpc-contract/buf.yaml new file mode 100644 index 0000000..5565f6e --- /dev/null +++ b/grpc/grpc-contract/buf.yaml @@ -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/grpc/grpc-contract +# buf lint +# buf breaking --against '#subdir=src/grpc/grpc-contract' +# +# No dependencies: the only imports are protoc's own well-known types (google/protobuf/*.proto). +version: v2 +modules: + - path: src/main/proto +lint: + use: + - STANDARD +breaking: + # FILE, not WIRE or WIRE_JSON. Wire compatibility alone would let a field rename or a Java package + # move through as "compatible" while every generated consumer stops compiling. + use: + - FILE diff --git a/grpc/grpc-contract/build.gradle b/grpc/grpc-contract/build.gradle new file mode 100644 index 0000000..8e93d9a --- /dev/null +++ b/grpc/grpc-contract/build.gradle @@ -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/.*' +} diff --git a/grpc/grpc-codegen/gradle.lockfile b/grpc/grpc-contract/gradle.lockfile similarity index 83% rename from grpc/grpc-codegen/gradle.lockfile rename to grpc/grpc-contract/gradle.lockfile index e2c9585..beb6fc2 100644 --- a/grpc/grpc-codegen/gradle.lockfile +++ b/grpc/grpc-contract/gradle.lockfile @@ -23,6 +23,7 @@ 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 @@ -34,7 +35,7 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnota io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.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 @@ -51,7 +52,7 @@ 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.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 @@ -59,17 +60,17 @@ 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.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,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,testRuntimeClasspath +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 @@ -81,4 +82,4 @@ org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath +empty=protobuf,testProtobuf diff --git a/grpc/grpc-proto-contract/src/main/resources/proto/hyeonworks/grpc/common/v1/error.proto b/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/error.proto similarity index 95% rename from grpc/grpc-proto-contract/src/main/resources/proto/hyeonworks/grpc/common/v1/error.proto rename to grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/error.proto index e28a028..b8324ee 100644 --- a/grpc/grpc-proto-contract/src/main/resources/proto/hyeonworks/grpc/common/v1/error.proto +++ b/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/error.proto @@ -1,9 +1,9 @@ syntax = "proto3"; -package hyeonworks.grpc.common.v1; +package caskeleton.grpc.common.v1; option java_multiple_files = true; -option java_package = "hyeonworks.grpc.common.v1.generated"; +option java_package = "caskeleton.grpc.common.v1.generated"; option java_outer_classname = "ErrorProto"; import "google/protobuf/duration.proto"; diff --git a/grpc/grpc-proto-contract/src/main/resources/proto/hyeonworks/grpc/common/v1/stream.proto b/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/stream.proto similarity index 95% rename from grpc/grpc-proto-contract/src/main/resources/proto/hyeonworks/grpc/common/v1/stream.proto rename to grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/stream.proto index 67bf8a3..f2c5e81 100644 --- a/grpc/grpc-proto-contract/src/main/resources/proto/hyeonworks/grpc/common/v1/stream.proto +++ b/grpc/grpc-contract/src/main/proto/caskeleton/grpc/common/v1/stream.proto @@ -1,9 +1,9 @@ syntax = "proto3"; -package hyeonworks.grpc.common.v1; +package caskeleton.grpc.common.v1; option java_multiple_files = true; -option java_package = "hyeonworks.grpc.common.v1.generated"; +option java_package = "caskeleton.grpc.common.v1.generated"; option java_outer_classname = "StreamProto"; // The Stable server-streaming envelope. diff --git a/grpc/grpc-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcContractGeneratedCodeTest.java b/grpc/grpc-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcContractGeneratedCodeTest.java new file mode 100644 index 0000000..0a67e16 --- /dev/null +++ b/grpc/grpc-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcContractGeneratedCodeTest.java @@ -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"); + } +} diff --git a/grpc/grpc-core-api/build.gradle b/grpc/grpc-core-api/build.gradle index ddde61d..84fc01a 100644 --- a/grpc/grpc-core-api/build.gradle +++ b/grpc/grpc-core-api/build.gradle @@ -1,5 +1,6 @@ plugins { id 'ca.platform-module' + id 'java-test-fixtures' } // The platform's port layer: identifiers, method policy, execution evidence, failure model, @@ -10,4 +11,8 @@ plugins { // a transport" is verifiable instead of aspirational — the same rule `messaging-core-api` holds. // A type here may not name io.grpc, Spring, Netty, protobuf or a database. dependencies { + // Test fixtures only, never main: the operation-ledger fake and the contract that both it and + // the JPA adapter must pass, so the fake cannot allow a transition the database refuses. + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } diff --git a/grpc/grpc-core-api/gradle.lockfile b/grpc/grpc-core-api/gradle.lockfile index e2c9585..13a5bab 100644 --- a/grpc/grpc-core-api/gradle.lockfile +++ b/grpc/grpc-core-api/gradle.lockfile @@ -1,40 +1,40 @@ # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.errorprone:error_prone_annotations:2.41.0=spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.puppycrawl.tools:checkstyle:13.5.0=checkstyle commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs @@ -50,32 +50,32 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor org.reflections:reflections:0.10.2=checkstyle org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudget.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudget.java index 99befcd..865f061 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudget.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudget.java @@ -1,5 +1,6 @@ package dev.caskeleton.grpc.api.context; +import dev.caskeleton.grpc.api.policy.GrpcTransportLimits; import java.util.Map; /** @@ -30,7 +31,7 @@ public record GrpcMetadataBudget(int maxTotalBytes, int maxUserDefinedBytes, int /** The platform default: 8 KiB total, 4 KiB of it user-defined, at most 32 entries. */ public static GrpcMetadataBudget standard() { - return new GrpcMetadataBudget(8192, 4096, 32); + return new GrpcMetadataBudget(GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, 4096, 32); } /** diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudget.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudget.java index b41258a..02a8cbb 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudget.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudget.java @@ -1,6 +1,7 @@ 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 @@ -9,17 +10,40 @@ import java.time.Duration; *

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

The budget is an absolute deadline on a monotonic nanosecond clock, so {@link #remaining()} + * shrinks and {@link #expired()} turns true as time passes. A request context carries one budget + * for the whole call; a budget that remembered only the duration it started with would hand every + * later dependency call the full original time. */ -public record GrpcDeadlineBudget(Duration remaining, GrpcDeadlineProfile profile) { +public final class GrpcDeadlineBudget { - /** Rejects a budget with no time in it. */ - public GrpcDeadlineBudget { - if (remaining == null || profile == null) { - throw new IllegalArgumentException("a deadline budget needs a remaining time and a profile"); + 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; } /** @@ -31,6 +55,12 @@ public record GrpcDeadlineBudget(Duration remaining, GrpcDeadlineProfile profile */ 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"); } @@ -42,17 +72,13 @@ public record GrpcDeadlineBudget(Duration remaining, GrpcDeadlineProfile profile throw new IllegalArgumentException( "a Stable unary call requires a positive deadline; got " + parentRemaining); } - Duration bounded = - parentRemaining.compareTo(profile.total()) <= 0 ? parentRemaining : profile.total(); - Duration afterReserve = bounded.minus(profile.safetyMargin()); - return new GrpcDeadlineBudget( - afterReserve.isNegative() ? Duration.ZERO : afterReserve, profile); + return new GrpcDeadlineBudget(afterReserve(parentRemaining, profile), profile, nanoClock); } /** * Derives the budget for a downstream dependency call under {@code downstream}. * - *

Takes the shorter of what is left here and what the downstream profile allows, then + *

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. */ @@ -60,11 +86,18 @@ public record GrpcDeadlineBudget(Duration remaining, GrpcDeadlineProfile profile if (downstream == null) { throw new IllegalArgumentException("a downstream budget needs a profile"); } - Duration bounded = - remaining.compareTo(downstream.total()) <= 0 ? remaining : downstream.total(); - Duration afterReserve = bounded.minus(downstream.safetyMargin()); - return new GrpcDeadlineBudget( - afterReserve.isNegative() ? Duration.ZERO : afterReserve, downstream); + 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; } /** @@ -75,11 +108,23 @@ public record GrpcDeadlineBudget(Duration remaining, GrpcDeadlineProfile profile * investigates the wrong system. */ public boolean canStartDependencyCall() { - return remaining.compareTo(profile.minimumAttemptBudget()) >= 0 && !remaining.isZero(); + Duration left = remaining(); + return !left.isZero() && left.compareTo(profile.minimumAttemptBudget()) >= 0; } /** Whether any time is left at all. */ public boolean expired() { - return remaining.isZero() || remaining.isNegative(); + return remaining().isZero(); + } + + @Override + public String toString() { + return "GrpcDeadlineBudget[remaining=" + remaining() + ", profile=" + profile + "]"; + } + + private static Duration afterReserve(Duration available, GrpcDeadlineProfile profile) { + Duration bounded = available.compareTo(profile.total()) <= 0 ? available : profile.total(); + Duration afterReserve = bounded.minus(profile.safetyMargin()); + return afterReserve.isNegative() ? Duration.ZERO : afterReserve; } } diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentity.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentity.java index b4dab91..bfd5bec 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentity.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentity.java @@ -16,6 +16,13 @@ import dev.caskeleton.grpc.core.GrpcMethodName; 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()) { @@ -30,6 +37,24 @@ public record GrpcOperationIdentity( 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. */ diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java index 9ab94f6..4342bde 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java @@ -40,6 +40,18 @@ public interface GrpcOperationLedger { /** Marks a claim terminally failed. */ void markFailed(GrpcOperationIdentity identity, Instant now); + /** + * Re-claims a {@code FAILED_TERMINAL} record for a new attempt of the same request. + * + *

A compare-and-set to {@code IN_PROGRESS}, atomic like {@link #claim}: of two concurrent + * re-claims exactly one returns true. A record in any other state, or made for a different + * request, is left untouched. A retry that proceeds without winning this leaves its commit with + * no owner and runs concurrently with every other retry of the same key. + * + * @return true when this call now owns the record as a fresh attempt claimed at {@code now} + */ + boolean reclaimFailed(GrpcOperationIdentity identity, String requestFingerprint, Instant now); + /** * Releases a claim that will never complete, so the caller may try again. * diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java index 2908b57..2c2cfaa 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java @@ -12,7 +12,10 @@ public enum GrpcOperationLedgerState { IN_PROGRESS(false), /** Committed, with a replayable outcome. */ COMMITTED(true), - /** Failed in a way that will not succeed on repetition. */ + /** + * The attempt failed and changed nothing. A retry of the same request may reclaim it (one winner) + * and run again; see {@code GrpcOperationLedger.reclaimFailed}. + */ FAILED_TERMINAL(true); private final boolean terminal; diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicy.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicy.java index 019a69d..3a6f872 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicy.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicy.java @@ -75,8 +75,8 @@ public record GrpcMethodPolicy( deadline, WaitForReadyPolicy.DISABLED, true, - 4 * 1024 * 1024, - 4 * 1024 * 1024); + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES); } /** A state-changing unary method that refuses explicit retry. */ @@ -89,8 +89,8 @@ public record GrpcMethodPolicy( deadline, WaitForReadyPolicy.DISABLED, false, - 4 * 1024 * 1024, - 4 * 1024 * 1024); + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES); } /** Whether this method may be hedged. */ diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcTransportLimits.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcTransportLimits.java new file mode 100644 index 0000000..c8eab4d --- /dev/null +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/policy/GrpcTransportLimits.java @@ -0,0 +1,21 @@ +package dev.caskeleton.grpc.api.policy; + +/** + * The platform's default transport bounds, stated once. + * + *

The server profile, the named channel profiles, the per-method size profile, the method policy + * defaults and the metadata budget all start from these numbers. They used to be five copies of the + * same literals, and a copy that drifts is a method that promises a message size its server + * rejects; {@code GrpcPlatformStartupValidator} refuses that combination, and it can only do so + * cheaply when the defaults agree by construction. + */ +public final class GrpcTransportLimits { + + /** Largest message a Stable method accepts or sends by default: 1 MiB. */ + public static final int DEFAULT_MAX_MESSAGE_BYTES = 1024 * 1024; + + /** Hard total for one call's metadata: 8 KiB. */ + public static final int DEFAULT_MAX_METADATA_BYTES = 8192; + + private GrpcTransportLimits() {} +} diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcMethodName.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcMethodName.java index 1db06d2..26528fb 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcMethodName.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcMethodName.java @@ -25,6 +25,16 @@ public record GrpcMethodName(GrpcServiceName service, String method) { throw new IllegalArgumentException( "method must be an UpperCamelCase proto method name; got '" + method + "'"); } + // The same bound parse() applies to the whole name, so both ways of making a method name + // accept exactly the same set of names. + int fullLength = service.value().length() + 1 + method.length(); + if (fullLength > GrpcIdentifiers.MAX_LENGTH) { + throw new IllegalArgumentException( + "full method name must be at most " + + GrpcIdentifiers.MAX_LENGTH + + " characters; got " + + fullLength); + } } /** diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableBuildInvariant.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableBuildInvariant.java deleted file mode 100644 index d86794a..0000000 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableBuildInvariant.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.grpc.core; - -import java.util.Set; - -/** - * Build-time invariants the Stable platform holds about its own module graph. - * - *

These are asserted from Java as well as from Gradle on purpose. The registry gate ({@code - * verifyCleanArchitectureDependencies}) is the one that fails a build, and it is the authority; - * this class is what a runtime component calls when it is handed a dependency set it did not - * compile against — a starter reading its own classpath, say — where the Gradle gate has nothing to - * look at. - */ -public final class GrpcStableBuildInvariant { - - private GrpcStableBuildInvariant() {} - - /** - * Whether a Stable module may depend on an Advanced one. - * - *

Always false, and it takes no argument for a reason: the answer does not vary by module, by - * capability or by environment. A method that could return true for some input would be the seam - * through which "just this one Advanced type in the starter" arrives. - */ - public static boolean advancedDependencyAllowed() { - return false; - } - - /** - * Fails when a Stable module's dependency set reaches an Advanced module. - * - * @throws IllegalStateException naming every advanced dependency found - */ - public static void requireNoAdvancedDependency(String moduleId, Set dependencies) { - GrpcIdentifiers.requireBounded(moduleId, "module id"); - if (dependencies == null) { - throw new IllegalArgumentException("dependency set must not be null"); - } - if (!GrpcStableModuleCatalog.standard().isStable(moduleId)) { - return; - } - Set leaks = GrpcStableModuleCatalog.advancedLeaks(dependencies); - if (!leaks.isEmpty()) { - throw new IllegalStateException( - "Stable module '" - + moduleId - + "' must not depend on advanced modules " - + leaks.stream().sorted().toList() - + "; advanced capabilities are reached through an explicit feature flag, never by " - + "being on the Stable classpath."); - } - } -} diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalog.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalog.java deleted file mode 100644 index b301a75..0000000 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalog.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.grpc.core; - -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * The exact set of Stable platform modules, and the exact set that is not Stable. - * - *

The Stable plan fixes its module list as a Global Constraint so that "this capability is - * Stable" is a fact with one owner instead of a property of whatever happens to be on a classpath. - * This repository's module registry ({@code src/config/architecture/modules.json}) is the SSOT for - * which Gradle projects exist; this catalog is the SSOT for which of them the Stable contract - * covers, and {@code GrpcStableModuleCatalogTest} holds the two together. - * - *

The names are this repository's leaf ids rather than the plan's, because the plan's four - * testkit modules are four strict test lanes here — see the adaptation design, §2. - */ -public record GrpcStableModuleCatalog(Set modules) { - - private static final Set STABLE = - Set.of( - "grpc-core-api", - "grpc-proto-contract", - "grpc-codegen", - "grpc-policy", - "grpc-server", - "grpc-client", - "grpc-discovery", - "grpc-admin", - "grpc-observability", - "grpc-operation-ledger-jpa", - "grpc-spring-boot-starter", - "grpc-testkit"); - - private static final Set ADVANCED = - Set.of( - "grpc-advanced-bootstrap", - "grpc-advanced-edition", - "grpc-advanced-streaming", - "grpc-advanced-resilience", - "grpc-advanced-compat", - "grpc-advanced-diagnostics"); - - /** Defensively copies, so a caller cannot widen the Stable set by mutating what it was given. */ - public GrpcStableModuleCatalog { - if (modules == null || modules.isEmpty()) { - throw new IllegalArgumentException("a module catalog needs at least one module"); - } - modules = Set.copyOf(modules); - } - - /** The Stable module set. */ - public static GrpcStableModuleCatalog standard() { - return new GrpcStableModuleCatalog(STABLE); - } - - /** The Advanced and Experimental module set, which is disjoint from {@link #standard()}. */ - public static Set advancedModules() { - return ADVANCED; - } - - /** Whether {@code moduleId} is part of the Stable contract. */ - public boolean isStable(String moduleId) { - return modules.contains(moduleId); - } - - /** - * The advanced module ids that appear in {@code candidateDependencies}. - * - *

Returned rather than thrown so a build or startup check can name every violation at once. A - * gate that reports the first advanced dependency it finds makes removing four of them a - * four-round conversation. - */ - public static Set advancedLeaks(Set candidateDependencies) { - Set leaks = new LinkedHashSet<>(candidateDependencies); - leaks.retainAll(ADVANCED); - return Set.copyOf(leaks); - } -} diff --git a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStatusCode.java b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStatusCode.java index 23e44d9..3c1a632 100644 --- a/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStatusCode.java +++ b/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStatusCode.java @@ -5,7 +5,7 @@ package dev.caskeleton.grpc.core; * *

The mirror is the point. The Stable plan requires the evidence and failure model to be * framework-free, and a failure context that names {@code io.grpc.Status} would put the transport - * inside the contract that exists to describe what the transport did. {@code grpc-policy} owns the + * inside the contract that exists to describe what the transport did. {@code grpc-runtime} owns the * translation in both directions and is tested against the real enum. */ public enum GrpcStatusCode { diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudgetTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudgetTest.java index 4a4851d..8241a1d 100644 --- a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudgetTest.java +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/context/GrpcMetadataBudgetTest.java @@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; class GrpcMetadataBudgetTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcMetadataKey CORRELATION = GrpcMetadataKey.ascii("x-correlation-id"); private static final GrpcMetadataKey IDEMPOTENCY = GrpcMetadataKey.ascii("x-idempotency-key"); diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudgetTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudgetTest.java index 58fd57a..a23bc99 100644 --- a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudgetTest.java +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/deadline/GrpcDeadlineBudgetTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import java.time.Instant; +import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -27,9 +28,11 @@ class GrpcDeadlineBudgetTest { @DisplayName("the budget takes the shorter of the parent remaining and the method default") void budgetTakesTheShorterOfParentAndMethodDefault() { GrpcDeadlineBudget fromShortParent = - GrpcDeadlineBudget.forEntryPoint(Duration.ofMillis(500), TWO_SECONDS); + GrpcDeadlineBudget.forEntryPoint( + Duration.ofMillis(500), TWO_SECONDS, GrpcDeadlineBudgetTest::frozenNanos); GrpcDeadlineBudget fromLongParent = - GrpcDeadlineBudget.forEntryPoint(Duration.ofSeconds(30), TWO_SECONDS); + GrpcDeadlineBudget.forEntryPoint( + Duration.ofSeconds(30), TWO_SECONDS, GrpcDeadlineBudgetTest::frozenNanos); assertThat(fromShortParent.remaining()) .isEqualTo(Duration.ofMillis(500).minus(TWO_SECONDS.safetyMargin())); @@ -44,7 +47,9 @@ class GrpcDeadlineBudgetTest { new GrpcDeadlineProfile( Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofMillis(100)); - GrpcDeadlineBudget budget = GrpcDeadlineBudget.forEntryPoint(Duration.ofSeconds(10), profile); + GrpcDeadlineBudget budget = + GrpcDeadlineBudget.forEntryPoint( + Duration.ofSeconds(10), profile, GrpcDeadlineBudgetTest::frozenNanos); assertThat(budget.remaining()).isEqualTo(Duration.ofSeconds(9)); assertThat(profile.usable()).isEqualTo(Duration.ofSeconds(9)); @@ -54,7 +59,8 @@ class GrpcDeadlineBudgetTest { @DisplayName("a downstream call never gets more time than its caller has left") void downstreamNeverExceedsTheCaller() { GrpcDeadlineBudget caller = - GrpcDeadlineBudget.forEntryPoint(Duration.ofMillis(400), TWO_SECONDS); + GrpcDeadlineBudget.forEntryPoint( + Duration.ofMillis(400), TWO_SECONDS, GrpcDeadlineBudgetTest::frozenNanos); GrpcDeadlineProfile generousDownstream = new GrpcDeadlineProfile(Duration.ofSeconds(30), Duration.ZERO, Duration.ofMillis(10)); @@ -77,6 +83,39 @@ class GrpcDeadlineBudgetTest { assertThat(new GrpcDeadlineBudget(Duration.ZERO, profile).canStartDependencyCall()).isFalse(); } + @Test + void aBudgetRunsOutAsTimePassesAfterItWasCreated() { + // given + AtomicLong nanos = new AtomicLong(); + GrpcDeadlineBudget budget = + new GrpcDeadlineBudget(Duration.ofMillis(300), TWO_SECONDS, nanos::get); + + // when + nanos.addAndGet(Duration.ofMillis(300).toNanos()); + + // then + assertThat(budget) + .extracting(GrpcDeadlineBudget::remaining, GrpcDeadlineBudget::expired) + .containsExactly(Duration.ZERO, true); + } + + @Test + void aDownstreamDerivedLaterGetsOnlyWhatIsLeftThen() { + // given + AtomicLong nanos = new AtomicLong(); + GrpcDeadlineBudget caller = + new GrpcDeadlineBudget(Duration.ofSeconds(1), TWO_SECONDS, nanos::get); + nanos.addAndGet(Duration.ofMillis(700).toNanos()); + + // when + GrpcDeadlineBudget downstream = + caller.deriveDownstream( + new GrpcDeadlineProfile(Duration.ofSeconds(30), Duration.ZERO, Duration.ofMillis(10))); + + // then + assertThat(downstream.remaining()).isEqualTo(Duration.ofMillis(300)); + } + @Test @DisplayName("a profile whose reserve leaves no usable time is refused") void profileWithNoUsableTimeIsRefused() { @@ -121,4 +160,8 @@ class GrpcDeadlineBudgetTest { .hasMessageContaining("charge-card") .hasMessageContaining("deadline-exceeded"); } + + private static long frozenNanos() { + return 0L; + } } diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/error/GrpcFailureContextTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/error/GrpcFailureContextTest.java index 930a743..c56aff7 100644 --- a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/error/GrpcFailureContextTest.java +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/error/GrpcFailureContextTest.java @@ -18,9 +18,9 @@ import org.junit.jupiter.api.Test; class GrpcFailureContextTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName WATCH = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/WatchDocuments"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); private static GrpcExecutionEvidence sentButUnanswered() { return new GrpcExecutionEvidence( @@ -99,7 +99,7 @@ class GrpcFailureContextTest { String summary = context.redactedSummary(); assertThat(summary) - .contains("hyeonworks.document.v1.DocumentService/CreateDocument") + .contains("caskeleton.document.v1.DocumentService/CreateDocument") .contains("DEADLINE_EXCEEDED") .contains("COMPLETION_UNKNOWN") .contains("RESOLVE_FIRST") diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentityTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentityTest.java new file mode 100644 index 0000000..2701a08 --- /dev/null +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/GrpcOperationIdentityTest.java @@ -0,0 +1,44 @@ +package dev.caskeleton.grpc.api.ledger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.grpc.core.GrpcMethodName; +import dev.caskeleton.grpc.core.GrpcServiceName; +import org.junit.jupiter.api.Test; + +class GrpcOperationIdentityTest { + + private static final GrpcMethodName CREATE = + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); + private static final String KEY_HASH = + "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"; + + @Test + void aCallerFingerprintWiderThanItsLedgerColumnIsRefused() { + // when + Throwable failure = + catchThrowable(() -> new GrpcOperationIdentity("c".repeat(257), CREATE, KEY_HASH)); + + // then + assertThat(failure) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("caller fingerprint must be at most 256"); + } + + @Test + void anIdentityWhoseStorageKeyWouldNotFitTheLedgerIsRefused() { + // given + GrpcMethodName longMethod = + new GrpcMethodName(new GrpcServiceName("p.S" + "s".repeat(197)), "M" + "m".repeat(54)); + + // when + Throwable failure = + catchThrowable(() -> new GrpcOperationIdentity("c".repeat(256), longMethod, KEY_HASH)); + + // then + assertThat(failure) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("storage key must be at most 512"); + } +} diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java new file mode 100644 index 0000000..ff2916f --- /dev/null +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java @@ -0,0 +1,11 @@ +package dev.caskeleton.grpc.api.ledger; + +class InMemoryOperationLedgerContractTest extends GrpcOperationLedgerContract { + + private final InMemoryOperationLedger ledger = new InMemoryOperationLedger(); + + @Override + protected GrpcOperationLedger ledger() { + return ledger; + } +} diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalogTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalogTest.java index fc52643..738c871 100644 --- a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalogTest.java +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/policy/GrpcMethodPolicyCatalogTest.java @@ -14,11 +14,11 @@ import org.junit.jupiter.api.Test; class GrpcMethodPolicyCatalogTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName WATCH = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/WatchDocuments"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); private static final GrpcDeadlineProfile TWO_SECONDS = GrpcDeadlineProfile.of(Duration.ofSeconds(2)); @@ -178,6 +178,6 @@ class GrpcMethodPolicyCatalogTest { assertThat(catalog.methods()) .extracting(GrpcMethodName::canonical) - .containsExactly("hyeonworks.document.v1.DocumentService/GetDocument"); + .containsExactly("caskeleton.document.v1.DocumentService/GetDocument"); } } diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcCoreIdentifiersTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcCoreIdentifiersTest.java index 08ce0a8..7940d71 100644 --- a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcCoreIdentifiersTest.java +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcCoreIdentifiersTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.core; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,12 +15,12 @@ class GrpcCoreIdentifiersTest { @DisplayName("a full method name round-trips through its canonical form") void methodNameRoundTripsThroughCanonicalForm() { GrpcMethodName parsed = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); - assertThat(parsed.canonical()).isEqualTo("hyeonworks.document.v1.DocumentService/GetDocument"); + assertThat(parsed.canonical()).isEqualTo("caskeleton.document.v1.DocumentService/GetDocument"); assertThat(parsed.method()).isEqualTo("GetDocument"); assertThat(parsed.service().simpleName()).isEqualTo("DocumentService"); - assertThat(parsed.service().protoPackage()).isEqualTo("hyeonworks.document.v1"); + assertThat(parsed.service().protoPackage()).isEqualTo("caskeleton.document.v1"); assertThat(GrpcMethodName.parse(parsed.canonical())).isEqualTo(parsed); } @@ -27,9 +28,9 @@ class GrpcCoreIdentifiersTest { @ValueSource( strings = { "DocumentService/Get", - "hyeonworks.document.v1.DocumentService", - "hyeonworks.document.v1.DocumentService/Get/Extra", - "hyeonworks.document.v1.DocumentService/getDocument" + "caskeleton.document.v1.DocumentService", + "caskeleton.document.v1.DocumentService/Get/Extra", + "caskeleton.document.v1.DocumentService/getDocument" }) @DisplayName("a name that is not exactly package.Service/Method is refused") void nonCanonicalMethodNamesAreRefused(String candidate) { @@ -37,6 +38,22 @@ class GrpcCoreIdentifiersTest { .isInstanceOf(IllegalArgumentException.class); } + @Test + @DisplayName("생성자로 만든 full method name도 parse와 같은 256자 한도를 넘으면 거부된다") + void constructedMethodNameLongerThanTheParseLimitIsRefused() { + // given + GrpcServiceName service = new GrpcServiceName("pkg.v1." + "S".repeat(200)); + String method = "M".repeat(100); + + // when + Throwable thrown = catchThrowable(() -> new GrpcMethodName(service, method)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("full method name must be at most 256 characters; got 308"); + } + @ParameterizedTest @ValueSource(strings = {"", "svc name", "Has Space", "tab\tseparated"}) @DisplayName("blank, whitespace and control-character identifiers are refused") diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalogTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalogTest.java deleted file mode 100644 index ff15677..0000000 --- a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalogTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.grpc.core; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Set; -import java.util.regex.Pattern; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -class GrpcStableModuleCatalogTest { - - @Test - @DisplayName("the Stable module set is exact and excludes every advanced module") - void stableModuleSetIsExactAndAdvancedIsExcluded() { - GrpcStableModuleCatalog catalog = GrpcStableModuleCatalog.standard(); - - assertThat(catalog.modules()) - .contains("grpc-core-api", "grpc-client", "grpc-server", "grpc-policy") - .doesNotContainAnyElementsOf(GrpcStableModuleCatalog.advancedModules()); - assertThat(GrpcStableBuildInvariant.advancedDependencyAllowed()).isFalse(); - } - - @Test - @DisplayName("the optional gRPC registry is exactly classified as Stable or Advanced") - void registryAndCatalogStayTogether() throws Exception { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - assertThat(candidate).as("repository root").isNotNull(); - String registry = Files.readString(candidate.resolve("src/config/architecture/modules.json")); - Pattern entry = - Pattern.compile( - "\\{[^{}]*\"id\"\\s*:\\s*\"(grpc-[^\"]+)\"[^{}]*" - + "\"build\"\\s*:\\s*\"optional-grpc\"[^{}]*\\}", - Pattern.DOTALL); - Set registered = - entry - .matcher(registry) - .results() - .map(result -> result.group(1)) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - Set classified = new java.util.HashSet<>(GrpcStableModuleCatalog.standard().modules()); - classified.addAll(GrpcStableModuleCatalog.advancedModules()); - - assertThat(registered).isNotEmpty().containsExactlyInAnyOrderElementsOf(classified); - } - - @Test - @DisplayName("the Stable and Advanced sets are disjoint") - void stableAndAdvancedAreDisjoint() { - GrpcStableModuleCatalog catalog = GrpcStableModuleCatalog.standard(); - - assertThat(GrpcStableModuleCatalog.advancedModules()).isNotEmpty().noneMatch(catalog::isStable); - } - - @Test - @DisplayName("a Stable module reaching an advanced module fails, naming every leak") - void stableModuleMayNotDependOnAdvanced() { - Set dependencies = - Set.of("grpc-core-api", "grpc-advanced-streaming", "grpc-advanced-compat"); - - assertThatThrownBy( - () -> - GrpcStableBuildInvariant.requireNoAdvancedDependency( - "grpc-spring-boot-starter", dependencies)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("grpc-spring-boot-starter") - .hasMessageContaining("grpc-advanced-streaming") - .hasMessageContaining("grpc-advanced-compat"); - } - - @Test - @DisplayName("a Stable module with only Stable dependencies passes") - void stableOnlyDependenciesPass() { - GrpcStableBuildInvariant.requireNoAdvancedDependency( - "grpc-server", Set.of("grpc-core-api", "grpc-policy")); - } - - @Test - @DisplayName("an advanced module is not judged by the Stable invariant") - void advancedModuleIsNotGovernedByTheStableRule() { - GrpcStableBuildInvariant.requireNoAdvancedDependency( - "grpc-advanced-compat", Set.of("grpc-advanced-bootstrap")); - } -} diff --git a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidenceTest.java b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidenceTest.java index c2cbf52..4b3b528 100644 --- a/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidenceTest.java +++ b/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/evidence/GrpcExecutionEvidenceTest.java @@ -11,9 +11,9 @@ import org.junit.jupiter.api.Test; class GrpcExecutionEvidenceTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName WATCH = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/WatchDocuments"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); @Test @DisplayName("seeing response headers never promotes the business axis to a confirmed commit") diff --git a/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java b/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java new file mode 100644 index 0000000..1ff769c --- /dev/null +++ b/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java @@ -0,0 +1,260 @@ +package dev.caskeleton.grpc.api.ledger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.grpc.core.GrpcMethodName; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.Test; + +/** + * The transitions every {@link GrpcOperationLedger} allows and refuses. + * + *

The in-memory fake and the JPA adapter (against real PostgreSQL) both extend this. A fake that + * allows a transition the database refuses lets every policy test pass for code that fails in + * production — which is how a retry of a {@code FAILED_TERMINAL} row once proceeded unclaimed. + */ +public abstract class GrpcOperationLedgerContract { + + private static final GrpcOperationIdentity ID = + new GrpcOperationIdentity( + "tenant-1.actor-1", + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"), + "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"); + private static final String FINGERPRINT = + "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + private static final String OTHER_FINGERPRINT = + "sha256:1122334455667788990011223344556677889900112233445566778899001122"; + private static final String OUTCOME = "outcome://document/42"; + private static final Instant NOW = Instant.parse("2026-09-25T10:00:00Z"); + + /** The ledger under test, holding no records when a test starts. */ + protected abstract GrpcOperationLedger ledger(); + + @Test + void theFirstClaimOfAnOperationIsOwnedByItsCaller() { + assertThat(ledger().claim(ID, FINGERPRINT, NOW)).isEmpty(); + } + + @Test + void aSecondClaimReadsTheFirstClaimInProgress() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + Optional second = + ledger().claim(ID, OTHER_FINGERPRINT, NOW.plusSeconds(1)); + + // then + assertThat(second) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::requestFingerprint, + GrpcOperationLedgerRecord::claimedAt) + .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, FINGERPRINT, NOW); + } + + @Test + void concurrentClaimsHaveExactlyOneOwner() throws Exception { + // when + List owned = concurrently(() -> ledger().claim(ID, FINGERPRINT, NOW).isEmpty()); + + // then + assertThat(owned).containsExactlyInAnyOrder(true, false); + } + + @Test + void aCommittedClaimKeepsTheOutcomeARetryReplays() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::outcomeReference, + GrpcOperationLedgerRecord::completedAt) + .containsExactly( + GrpcOperationLedgerState.COMMITTED, + Optional.of(OUTCOME), + Optional.of(NOW.plusSeconds(1))); + } + + @Test + void committingWithoutAClaimIsRefused() { + // when + Throwable refused = catchThrowable(() -> ledger().markCommitted(ID, OUTCOME, NOW)); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no claim exists"); + } + + @Test + void aCommittedClaimCannotBeCommittedAgain() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + + // when + Throwable refused = + catchThrowable( + () -> ledger().markCommitted(ID, "outcome://document/99", NOW.plusSeconds(2))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot transition again"); + } + + @Test + void aFailedClaimIsTerminal() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + ledger().markFailed(ID, NOW.plusSeconds(1)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::completedAt) + .containsExactly(GrpcOperationLedgerState.FAILED_TERMINAL, Optional.of(NOW.plusSeconds(1))); + } + + @Test + void aFailedClaimCannotBeCommittedWithoutBeingReclaimed() { + // given + failedClaim(); + + // when + Throwable refused = + catchThrowable(() -> ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(2))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot transition again"); + } + + @Test + void aFailedClaimIsReclaimedByARetryOfTheSameRequest() { + // given + failedClaim(); + + // when + boolean reclaimed = ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // then + assertThat(reclaimed).isTrue(); + } + + @Test + void aReclaimedClaimIsANewAttemptInProgressSinceTheReclaim() { + // given + failedClaim(); + + // when + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::claimedAt, + GrpcOperationLedgerRecord::completedAt) + .containsExactly( + GrpcOperationLedgerState.IN_PROGRESS, NOW.plusSeconds(2), Optional.empty()); + } + + @Test + void aReclaimedClaimCanBeCommitted() { + // given + failedClaim(); + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // when + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(3)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::outcomeReference) + .containsExactly(GrpcOperationLedgerState.COMMITTED, Optional.of(OUTCOME)); + } + + @Test + void aFailedClaimIsNotReclaimedForADifferentRequest() { + failedClaim(); + + assertThat(ledger().reclaimFailed(ID, OTHER_FINGERPRINT, NOW.plusSeconds(2))).isFalse(); + } + + @Test + void anInProgressClaimIsNotReclaimed() { + ledger().claim(ID, FINGERPRINT, NOW); + + assertThat(ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(1))).isFalse(); + } + + @Test + void aCommittedClaimIsNotReclaimed() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + + // when + boolean reclaimed = ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // then + assertThat(reclaimed).isFalse(); + } + + @Test + void concurrentReclaimsOfAFailedClaimHaveExactlyOneWinner() throws Exception { + // given + failedClaim(); + + // when + List reclaimed = + concurrently(() -> ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2))); + + // then + assertThat(reclaimed).containsExactlyInAnyOrder(true, false); + } + + private void failedClaim() { + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markFailed(ID, NOW.plusSeconds(1)); + } + + /** Runs {@code attempt} on two threads released together and returns both results. */ + private static List concurrently(Callable attempt) throws Exception { + CountDownLatch start = new CountDownLatch(1); + Callable gated = + () -> { + start.await(); + return attempt.call(); + }; + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(gated); + Future second = executor.submit(gated); + start.countDown(); + return List.of(first.get(), second.get()); + } + } +} diff --git a/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java b/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java new file mode 100644 index 0000000..f08ddac --- /dev/null +++ b/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java @@ -0,0 +1,111 @@ +package dev.caskeleton.grpc.api.ledger; + +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * A hand-rolled ledger for tests of code that depends on {@link GrpcOperationLedger}. + * + *

{@code putIfAbsent} on a concurrent map is the in-memory equivalent of the unique constraint + * the real adapter relies on, and {@code replace(key, expected, next)} of its conditional update, + * so claim and re-claim are atomic here for the same reason they are there. The transitions match + * the JPA adapter's because {@link GrpcOperationLedgerContract} runs against both; a fake that + * allowed more would let the policy tests pass for code the database refuses. + */ +public final class InMemoryOperationLedger implements GrpcOperationLedger { + + private final ConcurrentMap records = + new ConcurrentHashMap<>(); + private volatile boolean unavailable; + + /** Makes every read fail, so the UNKNOWN path can be exercised. */ + public void makeUnavailable() { + unavailable = true; + } + + @Override + public Optional claim( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + GrpcOperationLedgerRecord existing = + records.putIfAbsent( + identity.storageKey(), + GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); + return Optional.ofNullable(existing); + } + + @Override + public Optional find(GrpcOperationIdentity identity) { + if (unavailable) { + throw new IllegalStateException("ledger unavailable"); + } + return Optional.ofNullable(records.get(identity.storageKey())); + } + + @Override + public void markCommitted(GrpcOperationIdentity identity, String outcomeReference, Instant now) { + GrpcOperationLedgerRecord committed = + records.computeIfPresent( + identity.storageKey(), + (key, existing) -> + finish( + existing, + GrpcOperationLedgerState.COMMITTED, + Optional.of(outcomeReference), + now)); + if (committed == null) { + throw new IllegalStateException( + "cannot commit operation '" + identity.storageKey() + "': no claim exists"); + } + } + + @Override + public void markFailed(GrpcOperationIdentity identity, Instant now) { + records.computeIfPresent( + identity.storageKey(), + (key, existing) -> + finish(existing, GrpcOperationLedgerState.FAILED_TERMINAL, Optional.empty(), now)); + } + + @Override + public boolean reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + GrpcOperationLedgerRecord current = records.get(identity.storageKey()); + return current != null + && current.state() == GrpcOperationLedgerState.FAILED_TERMINAL + && current.sameRequestAs(requestFingerprint) + && records.replace( + identity.storageKey(), + current, + GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); + } + + @Override + public void release(GrpcOperationIdentity identity) { + records.remove(identity.storageKey()); + } + + // Only an IN_PROGRESS claim finishes; a terminal row is re-opened by reclaimFailed alone. + private static GrpcOperationLedgerRecord finish( + GrpcOperationLedgerRecord existing, + GrpcOperationLedgerState state, + Optional outcomeReference, + Instant now) { + if (existing.state() != GrpcOperationLedgerState.IN_PROGRESS) { + throw new IllegalStateException( + "operation '" + + existing.identity().storageKey() + + "' is already " + + existing.state() + + " and cannot transition again"); + } + return new GrpcOperationLedgerRecord( + existing.identity(), + state, + existing.requestFingerprint(), + outcomeReference, + existing.claimedAt(), + Optional.of(now)); + } +} diff --git a/grpc/grpc-discovery/build.gradle b/grpc/grpc-discovery/build.gradle deleted file mode 100644 index bee89e7..0000000 --- a/grpc/grpc-discovery/build.gradle +++ /dev/null @@ -1,11 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Stable discovery: Static/DNS resolvers, pick_first/round_robin load balancing, and the -// Kubernetes VIP / headless / mesh routing profiles. Custom resolvers, custom load balancers and -// xDS are Advanced and are refused here by GrpcDiscoveryPolicyValidator. -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-client') -} diff --git a/grpc/grpc-discovery/gradle.lockfile b/grpc/grpc-discovery/gradle.lockfile deleted file mode 100644 index 9369e83..0000000 --- a/grpc/grpc-discovery/gradle.lockfile +++ /dev/null @@ -1,91 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.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= diff --git a/grpc/grpc-observability/src/test/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicyTest.java b/grpc/grpc-observability/src/test/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicyTest.java index f8231bd..6cb5ebd 100644 --- a/grpc/grpc-observability/src/test/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicyTest.java +++ b/grpc/grpc-observability/src/test/java/dev/caskeleton/grpc/observability/GrpcMetricCardinalityPolicyTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; class GrpcMetricCardinalityPolicyTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static GrpcRpcObservation observation(int attempts, GrpcCompletionOutcome outcome) { return new GrpcRpcObservation( diff --git a/grpc/grpc-operation-ledger-jpa/build.gradle b/grpc/grpc-operation-ledger-jpa/build.gradle index a4f9708..9ecb4dd 100644 --- a/grpc/grpc-operation-ledger-jpa/build.gradle +++ b/grpc/grpc-operation-ledger-jpa/build.gradle @@ -1,13 +1,20 @@ plugins { - id 'ca.auxiliary-source-set' id 'ca.platform-module' } -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main' +testing { + suites { + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + } + } } } +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly +} // Durable mutation idempotency: the operation ledger entity, its state machine, the vendor-neutral // repository port and the Spring Data JPA binding, plus the migration that owns the unique @@ -26,6 +33,10 @@ dependencies { integrationTestImplementation 'org.testcontainers:testcontainers-postgresql' integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' integrationTestImplementation 'org.postgresql:postgresql' + + // The shared ledger contract, run against this adapter through a real JPA provider. + integrationTestImplementation testFixtures(project(':grpc:grpc-core-api')) + integrationTestRuntimeOnly 'org.hibernate.orm:hibernate-core' } strictTestLanes { diff --git a/grpc/grpc-operation-ledger-jpa/gradle.lockfile b/grpc/grpc-operation-ledger-jpa/gradle.lockfile index 3647258..d9b0741 100644 --- a/grpc/grpc-operation-ledger-jpa/gradle.lockfile +++ b/grpc/grpc-operation-ledger-jpa/gradle.lockfile @@ -2,6 +2,7 @@ # Manual edits can break the build and are not advised. # This file is expected to be part of source control. com.fasterxml.jackson.core:jackson-annotations:2.21=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.fasterxml:classmate:1.7.3=integrationTestRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath @@ -30,6 +31,7 @@ com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrat com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.sun.istack:istack-commons-runtime:4.1.2=integrationTestRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle @@ -41,8 +43,12 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integratio io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=integrationTestRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.inject:jakarta.inject-api:2.0.1=integrationTestRuntimeClasspath jakarta.persistence:jakarta.persistence-api:3.2.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.transaction:jakarta.transaction-api:2.0.1=integrationTestRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=integrationTestRuntimeClasspath javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -71,7 +77,14 @@ org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs +org.eclipse.angus:angus-activation:2.0.3=integrationTestRuntimeClasspath +org.glassfish.jaxb:jaxb-core:4.0.9=integrationTestRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:4.0.9=integrationTestRuntimeClasspath +org.glassfish.jaxb:txw2:4.0.9=integrationTestRuntimeClasspath +org.hibernate.models:hibernate-models:1.0.1=integrationTestRuntimeClasspath +org.hibernate.orm:hibernate-core:7.2.24.Final=integrationTestRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle +org.jboss.logging:jboss-logging:3.6.3.Final=integrationTestRuntimeClasspath org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java b/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java new file mode 100644 index 0000000..2d1e6b2 --- /dev/null +++ b/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java @@ -0,0 +1,185 @@ +package dev.caskeleton.grpc.ledger; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerContract; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; +import dev.caskeleton.grpc.core.GrpcMethodName; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.PersistenceConfiguration; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.util.Optional; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.SharedEntityManagerCreator; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Runs the ledger contract against {@link JpaGrpcOperationLedger} on Hibernate and PostgreSQL. + * + *

Every ledger call runs in its own transaction, standing in for the caller's business + * transaction; the two threads of a concurrency test therefore race as two real transactions. + */ +@Testcontainers(disabledWithoutDocker = true) +class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { + + @SuppressWarnings("resource") + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer("postgres:16-alpine") + .withDatabaseName("grpc") + .withUsername("grpc") + .withPassword("grpc"); + + private static EntityManagerFactory entityManagerFactory; + private static TransactionTemplate transactions; + private static JpaGrpcOperationLedger adapter; + private static GrpcOperationLedger ledger; + + @BeforeAll + static void startJpa() throws SQLException, IOException { + execute(migration()); + entityManagerFactory = + new PersistenceConfiguration("grpc-operation-ledger") + .managedClass(GrpcOperationLedgerEntity.class) + .property(PersistenceConfiguration.JDBC_URL, POSTGRES.getJdbcUrl()) + .property(PersistenceConfiguration.JDBC_USER, POSTGRES.getUsername()) + .property(PersistenceConfiguration.JDBC_PASSWORD, POSTGRES.getPassword()) + .createEntityManagerFactory(); + GrpcOperationLedgerRepository repository = + new JpaRepositoryFactory( + SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory)) + .getRepository(GrpcOperationLedgerRepository.class); + transactions = new TransactionTemplate(new JpaTransactionManager(entityManagerFactory)); + adapter = new JpaGrpcOperationLedger(repository); + ledger = new PerCallTransactionLedger(adapter, transactions); + } + + @AfterAll + static void stopJpa() { + entityManagerFactory.close(); + } + + @BeforeEach + void emptyTheLedger() throws SQLException { + execute("TRUNCATE grpc_operation_ledger"); + } + + @Override + protected GrpcOperationLedger ledger() { + return ledger; + } + + /** + * Adopters are told to claim and commit inside the business transaction. The claim loads the + * failed row into the persistence context, so without the re-claim clearing it the commit would + * read the stale FAILED_TERMINAL copy and refuse. + */ + @Test + void aRetryThatReclaimsAndCommitsInOneTransactionCommits() { + // given + GrpcOperationIdentity id = + new GrpcOperationIdentity( + "tenant-1.actor-1", + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"), + "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"); + String fingerprint = "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + Instant now = Instant.parse("2026-09-25T10:00:00Z"); + ledger.claim(id, fingerprint, now); + ledger.markFailed(id, now.plusSeconds(1)); + + // when + transactions.executeWithoutResult( + status -> { + adapter.claim(id, fingerprint, now.plusSeconds(2)); + adapter.reclaimFailed(id, fingerprint, now.plusSeconds(2)); + adapter.markCommitted(id, "outcome://document/42", now.plusSeconds(3)); + }); + + // then + assertThat(ledger.find(id)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::outcomeReference) + .containsExactly(GrpcOperationLedgerState.COMMITTED, Optional.of("outcome://document/42")); + } + + private static void execute(String sql) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private static String migration() throws IOException { + try (InputStream stream = + JpaGrpcOperationLedgerContractIT.class + .getClassLoader() + .getResourceAsStream("db/migration/grpc/V001__create_grpc_operation_ledger.sql")) { + if (stream == null) { + throw new IOException("gRPC operation-ledger migration is missing"); + } + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } + + /** Runs each call in its own transaction, as a caller's business transaction would. */ + private record PerCallTransactionLedger( + JpaGrpcOperationLedger delegate, TransactionTemplate transactions) + implements GrpcOperationLedger { + + @Override + public Optional claim( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + return transactions.execute(status -> delegate.claim(identity, requestFingerprint, now)); + } + + @Override + public Optional find(GrpcOperationIdentity identity) { + return transactions.execute(status -> delegate.find(identity)); + } + + @Override + public void markCommitted( + GrpcOperationIdentity identity, String outcomeReference, Instant now) { + transactions.executeWithoutResult( + status -> delegate.markCommitted(identity, outcomeReference, now)); + } + + @Override + public void markFailed(GrpcOperationIdentity identity, Instant now) { + transactions.executeWithoutResult(status -> delegate.markFailed(identity, now)); + } + + @Override + public boolean reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + return Boolean.TRUE.equals( + transactions.execute( + status -> delegate.reclaimFailed(identity, requestFingerprint, now))); + } + + @Override + public void release(GrpcOperationIdentity identity) { + transactions.executeWithoutResult(status -> delegate.release(identity)); + } + } +} diff --git a/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java b/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java index 5f72d6d..f1823b8 100644 --- a/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java +++ b/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java @@ -62,6 +62,36 @@ public interface GrpcOperationLedgerRepository @Param("requestFingerprint") String requestFingerprint, @Param("claimedAt") Instant claimedAt); + /** + * Re-claims a terminally failed row as a new attempt of the same request. + * + *

One conditional update, so PostgreSQL's row lock decides the race: a concurrent second + * re-claim re-evaluates the condition against the winner's {@code IN_PROGRESS} row and updates + * nothing. It clears the persistence context, because a row this transaction already loaded (the + * claim's read-on-conflict does) would otherwise still read {@code FAILED_TERMINAL} and refuse + * the commit. + * + * @return one when this caller re-claimed the row, zero otherwise + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Transactional + @Query( + value = + """ + UPDATE grpc_operation_ledger + SET state = 'IN_PROGRESS', + claimed_at = :claimedAt, + completed_at = NULL + WHERE storage_key = :storageKey + AND state = 'FAILED_TERMINAL' + AND request_fingerprint = :requestFingerprint + """, + nativeQuery = true) + int tryReclaimFailed( + @Param("storageKey") String storageKey, + @Param("requestFingerprint") String requestFingerprint, + @Param("claimedAt") Instant claimedAt); + /** Updates an existing claim after it has been loaded. */ GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity); diff --git a/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java b/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java index 7c03805..7cd1afc 100644 --- a/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java +++ b/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java @@ -50,7 +50,19 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { if (inserted != 0) { throw new IllegalStateException("claim insert affected an unexpected row count: " + inserted); } - return repository.findById(identity.storageKey()).map(entity -> entity.toRecord(identity)); + // Zero rows means another claim holds the key. An empty read now means that owner released it + // in between; treating that as "ours" would run the mutation without a claim row to guard it. + return Optional.of( + repository + .findById(identity.storageKey()) + .orElseThrow( + () -> + new IllegalStateException( + "claim for '" + + identity.storageKey() + + "' conflicted, but there was no row to read; the other owner released" + + " it in between. Retry the claim.")) + .toRecord(identity)); } @Override @@ -88,6 +100,13 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { }); } + @Override + public boolean reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + requireIdentity(identity); + return repository.tryReclaimFailed(identity.storageKey(), requestFingerprint, now) == 1; + } + @Override public void release(GrpcOperationIdentity identity) { requireIdentity(identity); diff --git a/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java b/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java index fba811e..8da7c64 100644 --- a/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java +++ b/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.ledger; 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.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; @@ -23,7 +24,7 @@ import org.junit.jupiter.api.Test; class GrpcOperationLedgerRepositoryTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); private static final String FINGERPRINT = "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; @@ -40,7 +41,7 @@ class GrpcOperationLedgerRepositoryTest { * putIfAbsent} and therefore tested the database constraint we wished save() would hit rather * than the merge behavior it actually uses. */ - private static final class InMemoryRepository implements GrpcOperationLedgerRepository { + private static class InMemoryRepository implements GrpcOperationLedgerRepository { private final ConcurrentMap rows = new ConcurrentHashMap<>(); @Override @@ -59,6 +60,12 @@ class GrpcOperationLedgerRepositoryTest { return rows.putIfAbsent(storageKey, claim) == null ? 1 : 0; } + @Override + public int tryReclaimFailed(String storageKey, String requestFingerprint, Instant claimedAt) { + throw new UnsupportedOperationException( + "the re-claim is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); + } + @Override public GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity) { rows.put(entity.getStorageKey(), entity); @@ -118,6 +125,34 @@ class GrpcOperationLedgerRepositoryTest { assertThat(second.get().sameRequestAs(FINGERPRINT)).isTrue(); } + @Test + void aConflictWhoseRowVanishedBeforeTheReadIsNotTakenAsOwnership() { + // given + InMemoryRepository conflictThenReleased = + new InMemoryRepository() { + @Override + public int tryInsertClaim( + String storageKey, + String callerFingerprint, + String fullMethodName, + String idempotencyKeyHash, + String requestFingerprint, + Instant claimedAt) { + return 0; // another owner held the key and released it before this read + } + }; + GrpcOperationLedger racing = new JpaGrpcOperationLedger(conflictThenReleased); + + // when + Throwable failure = + catchThrowable(() -> racing.claim(identity("tenant-1.actor-1"), FINGERPRINT, NOW)); + + // then + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no row to read"); + } + @Test @DisplayName("one caller's key does not collide with another's") void callersDoNotCollide() { diff --git a/grpc/grpc-policy/build.gradle b/grpc/grpc-policy/build.gradle deleted file mode 100644 index 17a4f5b..0000000 --- a/grpc/grpc-policy/build.gradle +++ /dev/null @@ -1,16 +0,0 @@ -plugins { - id 'ca.grpc-platform-module' -} - -// Validation, context propagation, status/rich-error mapping, TLS/credential profiles, deadline -// and cancellation, retry ownership and eligibility, idempotency and completion recovery, server -// streaming, payload size and compression. - -dependencies { - api project(':grpc:grpc-core-api') - - // api: interceptors, context binders and the error mapper name io.grpc types in public - // signatures, so an adopter cannot compile against this module without them. - api "io.grpc:grpc-api" - api "io.grpc:grpc-stub" -} diff --git a/grpc/grpc-policy/gradle.lockfile b/grpc/grpc-policy/gradle.lockfile deleted file mode 100644 index 9369e83..0000000 --- a/grpc/grpc-policy/gradle.lockfile +++ /dev/null @@ -1,91 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.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= diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamProfile.java b/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamProfile.java deleted file mode 100644 index f999c26..0000000 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamProfile.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.grpc.streaming; - -/** - * How one streaming method behaves before any message is sent. - * - *

{@code liveEventsBeforeSnapshotComplete} is the setting worth arguing about. Delivering live - * events while the snapshot is still being sent gives the client fresher data and an ordering it - * cannot reconstruct: it may see the update to a row before the row itself. Buffering them is - * correct and costs memory bounded by the snapshot duration. Neither is right for every method, - * which is why this is a per-method decision rather than a platform default. - */ -public record GrpcStreamProfile( - boolean snapshotFirst, - boolean liveEventsBeforeSnapshotComplete, - boolean resumable, - int maxBufferedMessages, - long maxBufferedBytes) { - - /** Refuses an incoherent profile. */ - public GrpcStreamProfile { - if (maxBufferedMessages < 1) { - throw new IllegalArgumentException("a stream buffers at least one message"); - } - if (maxBufferedBytes < 1L) { - throw new IllegalArgumentException("a stream needs a positive byte bound"); - } - if (liveEventsBeforeSnapshotComplete && !snapshotFirst) { - throw new IllegalArgumentException( - "a profile without a snapshot cannot describe what happens before the snapshot completes"); - } - } - - /** - * The Stable default: snapshot first, live events buffered until it completes, resumable. - * - *

Buffering is the default because the alternative delivers an update to a row before the row, - * and a client that has to tolerate that is a client doing the platform's ordering work. - */ - public static GrpcStreamProfile snapshotThenLive() { - return new GrpcStreamProfile(true, false, true, 256, 8L * 1024L * 1024L); - } - - /** A live-only stream with no snapshot phase. */ - public static GrpcStreamProfile liveOnly() { - return new GrpcStreamProfile(false, false, true, 256, 8L * 1024L * 1024L); - } -} diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/InMemoryOperationLedger.java b/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/InMemoryOperationLedger.java deleted file mode 100644 index 8d79058..0000000 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/InMemoryOperationLedger.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.grpc.idempotency; - -import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; -import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; -import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; -import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * A hand-rolled ledger for the policy tests. - * - *

{@code putIfAbsent} on a concurrent map is the in-memory equivalent of the unique constraint - * the real adapter relies on, so the claim is atomic here for the same reason it is there. A fake - * that read and then wrote would let the policy tests pass while the property they exist to check - * does not hold. - */ -final class InMemoryOperationLedger implements GrpcOperationLedger { - - private final ConcurrentMap records = - new ConcurrentHashMap<>(); - private boolean unavailable; - - /** Makes every read fail, so the UNKNOWN path can be exercised. */ - void makeUnavailable() { - unavailable = true; - } - - @Override - public Optional claim( - GrpcOperationIdentity identity, String requestFingerprint, Instant now) { - GrpcOperationLedgerRecord existing = - records.putIfAbsent( - identity.storageKey(), - GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); - return Optional.ofNullable(existing); - } - - @Override - public Optional find(GrpcOperationIdentity identity) { - if (unavailable) { - throw new IllegalStateException("ledger unavailable"); - } - return Optional.ofNullable(records.get(identity.storageKey())); - } - - @Override - public void markCommitted(GrpcOperationIdentity identity, String outcomeReference, Instant now) { - records.computeIfPresent( - identity.storageKey(), - (key, existing) -> - new GrpcOperationLedgerRecord( - existing.identity(), - GrpcOperationLedgerState.COMMITTED, - existing.requestFingerprint(), - Optional.of(outcomeReference), - existing.claimedAt(), - Optional.of(now))); - } - - @Override - public void markFailed(GrpcOperationIdentity identity, Instant now) { - records.computeIfPresent( - identity.storageKey(), - (key, existing) -> - new GrpcOperationLedgerRecord( - existing.identity(), - GrpcOperationLedgerState.FAILED_TERMINAL, - existing.requestFingerprint(), - Optional.empty(), - existing.claimedAt(), - Optional.of(now))); - } - - @Override - public void release(GrpcOperationIdentity identity) { - records.remove(identity.storageKey()); - } -} diff --git a/grpc/grpc-proto-contract/build.gradle b/grpc/grpc-proto-contract/build.gradle deleted file mode 100644 index d2c9d36..0000000 --- a/grpc/grpc-proto-contract/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -// Schema source of truth: the `.proto` files plus the rule engine that judges them. -// -// No protobuf plugin and no protoc invocation here — see -// docs/superpowers/specs/2026-08-30-grpc-platform-adaptation-design.md D6. The validator reads -// `.proto` text and enforces the Stable style manifest (proto3 + explicit optional, package -// versioning, reserved history, enum zero suffix, WKT allowlist), which is the invariant the plan -// owns; running protoc is a separate, gated decision. -dependencies { - api project(':grpc:grpc-core-api') -} diff --git a/grpc/grpc-proto-contract/gradle.lockfile b/grpc/grpc-proto-contract/gradle.lockfile deleted file mode 100644 index e2c9585..0000000 --- a/grpc/grpc-proto-contract/gradle.lockfile +++ /dev/null @@ -1,84 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.21.0=spotbugs -info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle -org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle -org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle -org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath -org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle -org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle -org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle -org.codehaus.plexus:plexus-utils:3.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit:junit-bom:6.1.0=spotbugs -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath -org.ow2.asm:asm-analysis:9.10.1=spotbugs -org.ow2.asm:asm-commons:9.10.1=spotbugs -org.ow2.asm:asm-tree:9.10.1=spotbugs -org.ow2.asm:asm-util:9.10.1=spotbugs -org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath diff --git a/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoContractValidator.java b/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoContractValidator.java deleted file mode 100644 index 94dd631..0000000 --- a/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoContractValidator.java +++ /dev/null @@ -1,447 +0,0 @@ -package dev.caskeleton.grpc.contract; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Judges committed {@code .proto} sources against {@link GrpcProtoStyleManifest} and the schema's - * own removal history. - * - *

A line scanner, not a Protobuf parser, and that is a deliberate limit rather than a shortcut. - * Everything this checks is a property of the source text a reviewer reads — the syntax line, the - * package, the two Java options, the zero enum value, the {@code reserved} declarations, the - * imports, the {@code map} fields, explicit presence. Semantics that need a compiled descriptor - * belong to {@code grpc-codegen}'s descriptor artifact, which is where a real {@code protoc} run - * would be consumed. - * - *

The removal history is an input rather than something inferred, because it cannot be inferred: - * a field that is simply gone from the current source is indistinguishable from one that never - * existed. Recording removals and checking them against {@code reserved} is the only way the "do - * not reuse a field number" rule survives the commit that deletes the field. - */ -public final class GrpcProtoContractValidator { - - /** Rule ids, so a build log and a review checklist use the same names. */ - public static final String RULE_PROTO3_SYNTAX = "PROTO3_SYNTAX"; - - /** The package must be {@code organization.domain.vMAJOR}. */ - public static final String RULE_PACKAGE_VERSIONED = "PACKAGE_VERSIONED"; - - /** {@code option java_multiple_files = true} must be present. */ - public static final String RULE_JAVA_MULTIPLE_FILES = "JAVA_MULTIPLE_FILES"; - - /** The generated Java package must not collide with a hand-written one. */ - public static final String RULE_JAVA_PACKAGE_SEPARATE = "JAVA_PACKAGE_SEPARATE"; - - /** An enum's zero value must end in {@code _UNSPECIFIED}. */ - public static final String RULE_ENUM_ZERO_UNSPECIFIED = "ENUM_ZERO_UNSPECIFIED"; - - /** A removed field number or name must be {@code reserved}. */ - public static final String RULE_RESERVED_HISTORY = "RESERVED_HISTORY"; - - /** A {@code google.protobuf} import must be on the allowlist. */ - public static final String RULE_WELL_KNOWN_TYPE_ALLOWLIST = "WELL_KNOWN_TYPE_ALLOWLIST"; - - /** A {@code map} field must be on the allowlist. */ - public static final String RULE_MAP_ALLOWLIST = "MAP_ALLOWLIST"; - - /** A field the manifest marks presence-required must be declared {@code optional}. */ - public static final String RULE_EXPLICIT_PRESENCE = "EXPLICIT_PRESENCE"; - - private static final Pattern SYNTAX = Pattern.compile("^\\s*syntax\\s*=\\s*\"([^\"]+)\"\\s*;"); - private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([A-Za-z0-9_.]+)\\s*;"); - private static final Pattern IMPORT = - Pattern.compile("^\\s*import\\s+(?:public\\s+|weak\\s+)?\"([^\"]+)\"\\s*;"); - private static final Pattern OPTION = - Pattern.compile("^\\s*option\\s+([A-Za-z0-9_]+)\\s*=\\s*(.+?)\\s*;"); - private static final Pattern SCOPE_OPEN = - Pattern.compile("^\\s*(message|enum|service|oneof)\\s+([A-Za-z0-9_]+)\\s*\\{"); - private static final Pattern ENUM_VALUE = - Pattern.compile("^\\s*([A-Za-z0-9_]+)\\s*=\\s*(-?\\d+)\\s*(?:\\[[^\\]]*\\])?\\s*;"); - private static final Pattern MAP_FIELD = - Pattern.compile("^\\s*map\\s*<[^>]+>\\s+([A-Za-z0-9_]+)\\s*=\\s*(\\d+)"); - private static final Pattern FIELD = - Pattern.compile( - "^\\s*(optional\\s+|repeated\\s+)?([A-Za-z0-9_.]+)\\s+([A-Za-z0-9_]+)\\s*=\\s*(\\d+)"); - private static final Pattern RESERVED_NUMBERS = - Pattern.compile("^\\s*reserved\\s+([^\";]*\\d[^\";]*);"); - private static final Pattern RESERVED_NAMES = - Pattern.compile("^\\s*reserved\\s+(\"[^;]*\")\\s*;"); - private static final Pattern QUOTED_NAME = Pattern.compile("\"([A-Za-z0-9_]+)\""); - private static final Pattern NUMBER = Pattern.compile("\\d+"); - private static final Pattern LINE_COMMENT = Pattern.compile("//.*$"); - - private final GrpcProtoStyleManifest manifest; - - /** Binds a validator to the manifest it judges against. */ - public GrpcProtoContractValidator(GrpcProtoStyleManifest manifest) { - if (manifest == null) { - throw new IllegalArgumentException("a validator needs a style manifest"); - } - this.manifest = manifest; - } - - /** - * What was removed from a schema, and therefore what must stay reserved. - * - *

Keys are message names as written in the file, nested ones qualified with a dot — {@code - * PreconditionFailure.Violation}. - */ - public record SchemaHistory( - Map> removedFieldNumbers, Map> removedFieldNames) { - - /** Copies both maps. */ - public SchemaHistory { - if (removedFieldNumbers == null || removedFieldNames == null) { - throw new IllegalArgumentException("a schema history needs both removal maps"); - } - removedFieldNumbers = copyOf(removedFieldNumbers); - removedFieldNames = copyOf(removedFieldNames); - } - - private static Map> copyOf(Map> source) { - Map> copy = new LinkedHashMap<>(); - source.forEach((key, value) -> copy.put(key, Set.copyOf(value))); - return Map.copyOf(copy); - } - - /** A schema nothing has been removed from yet. */ - public static SchemaHistory empty() { - return new SchemaHistory(Map.of(), Map.of()); - } - } - - /** Validates one file against the manifest, with no removal history to check. */ - public List validate(String fileName, String source) { - return validate(fileName, source, SchemaHistory.empty()); - } - - /** - * Validates one file against the manifest and its removal history. - * - * @return every violation found, in source order; empty when the file is compliant - */ - public List validate( - String fileName, String source, SchemaHistory history) { - if (fileName == null || fileName.isBlank()) { - throw new IllegalArgumentException("a proto file needs a name"); - } - if (source == null) { - throw new IllegalArgumentException("a proto file needs source text"); - } - if (history == null) { - throw new IllegalArgumentException("a schema history must be present; use empty()"); - } - - List violations = new ArrayList<>(); - Scan scan = scan(fileName, source, violations); - - checkFileHeader(fileName, scan, violations); - checkRemovalHistory(fileName, scan, history, violations); - return List.copyOf(violations); - } - - private void checkFileHeader( - String fileName, Scan scan, List violations) { - if (!"proto3".equals(scan.syntax)) { - violations.add( - GrpcProtoRuleViolation.ofFile( - RULE_PROTO3_SYNTAX, - fileName, - "Stable schema source must declare syntax = \"proto3\"; found " - + (scan.syntax == null ? "no syntax declaration" : "'" + scan.syntax + "'"))); - } - String expectedPrefix = manifest.organization() + "."; - if (scan.protoPackage == null) { - violations.add( - GrpcProtoRuleViolation.ofFile( - RULE_PACKAGE_VERSIONED, fileName, "no package declaration")); - } else if (!scan.protoPackage.startsWith(expectedPrefix) - || !scan.protoPackage.matches(".*\\.v[1-9]\\d*$")) { - violations.add( - new GrpcProtoRuleViolation( - RULE_PACKAGE_VERSIONED, - fileName, - scan.packageLine, - "package must be '" - + manifest.organization() - + "..v'; got '" - + scan.protoPackage - + "'")); - } - if (!"true".equals(scan.options.get("java_multiple_files"))) { - violations.add( - GrpcProtoRuleViolation.ofFile( - RULE_JAVA_MULTIPLE_FILES, - fileName, - "option java_multiple_files = true is required; one outer class per file hides every " - + "generated type behind a name the schema never mentions")); - } - String javaPackage = unquote(scan.options.get("java_package")); - if (javaPackage == null || javaPackage.isBlank()) { - violations.add( - GrpcProtoRuleViolation.ofFile( - RULE_JAVA_PACKAGE_SEPARATE, fileName, "option java_package is required")); - } else { - for (String handWritten : manifest.handWrittenJavaPackages()) { - if (javaPackage.equals(handWritten) || javaPackage.startsWith(handWritten + ".")) { - violations.add( - GrpcProtoRuleViolation.ofFile( - RULE_JAVA_PACKAGE_SEPARATE, - fileName, - "generated java_package '" - + javaPackage - + "' is inside hand-written package '" - + handWritten - + "'; generated and hand-written types must not share a package")); - } - } - } - } - - private static void checkRemovalHistory( - String fileName, Scan scan, SchemaHistory history, List violations) { - history - .removedFieldNumbers() - .forEach( - (message, numbers) -> { - Set reserved = scan.reservedNumbers.getOrDefault(message, Set.of()); - Set missing = new LinkedHashSet<>(numbers); - missing.removeAll(reserved); - if (!missing.isEmpty()) { - violations.add( - GrpcProtoRuleViolation.ofFile( - RULE_RESERVED_HISTORY, - fileName, - "message '" - + message - + "' removed field numbers " - + missing.stream().sorted().toList() - + " without reserving them; the next field added would reuse a number " - + "an old client still writes")); - } - }); - history - .removedFieldNames() - .forEach( - (message, names) -> { - Set reserved = scan.reservedNames.getOrDefault(message, Set.of()); - Set missing = new LinkedHashSet<>(names); - missing.removeAll(reserved); - if (!missing.isEmpty()) { - violations.add( - GrpcProtoRuleViolation.ofFile( - RULE_RESERVED_HISTORY, - fileName, - "message '" - + message - + "' removed field names " - + missing.stream().sorted().toList() - + " without reserving them; reusing the name changes the JSON contract")); - } - }); - } - - private Scan scan(String fileName, String source, List violations) { - Scan scan = new Scan(); - Deque scopeKinds = new ArrayDeque<>(); - Deque scopeNames = new ArrayDeque<>(); - int lineNumber = 0; - - for (String rawLine : source.lines().toList()) { - lineNumber++; - String line = LINE_COMMENT.matcher(rawLine).replaceAll(""); - if (line.isBlank()) { - continue; - } - - Matcher syntax = SYNTAX.matcher(line); - if (syntax.find()) { - scan.syntax = syntax.group(1); - continue; - } - Matcher packageMatcher = PACKAGE.matcher(line); - if (packageMatcher.find()) { - scan.protoPackage = packageMatcher.group(1); - scan.packageLine = lineNumber; - continue; - } - Matcher importMatcher = IMPORT.matcher(line); - if (importMatcher.find()) { - String importPath = importMatcher.group(1); - if (!manifest.wellKnownTypeAllowed(importPath)) { - violations.add( - new GrpcProtoRuleViolation( - RULE_WELL_KNOWN_TYPE_ALLOWLIST, - fileName, - lineNumber, - "import '" - + importPath - + "' is not on the well-known type allowlist; Any and Struct erase the " - + "schema they are supposed to describe, so each use is granted by name")); - } - continue; - } - Matcher option = OPTION.matcher(line); - if (option.find() && scopeKinds.isEmpty()) { - scan.options.put(option.group(1), option.group(2)); - continue; - } - - Matcher scopeOpen = SCOPE_OPEN.matcher(line); - if (scopeOpen.find()) { - scopeKinds.push(scopeOpen.group(1)); - scopeNames.push(qualify(scopeNames, scopeOpen.group(2))); - continue; - } - if (line.strip().startsWith("}")) { - if (!scopeKinds.isEmpty()) { - scopeKinds.pop(); - scopeNames.pop(); - } - continue; - } - if (scopeKinds.isEmpty()) { - continue; - } - - String scopeKind = scopeKinds.peek(); - String scopeName = scopeNames.peek(); - if ("enum".equals(scopeKind)) { - scanEnumValue(fileName, line, lineNumber, scopeName, violations); - } else if ("message".equals(scopeKind) || "oneof".equals(scopeKind)) { - scanMessageMember(fileName, line, lineNumber, scopeName, scan, violations); - } - } - return scan; - } - - private static void scanEnumValue( - String fileName, - String line, - int lineNumber, - String enumName, - List violations) { - Matcher value = ENUM_VALUE.matcher(line); - if (!value.find()) { - return; - } - if (!"0".equals(value.group(2))) { - return; - } - String name = value.group(1); - if (!name.endsWith("_UNSPECIFIED")) { - violations.add( - new GrpcProtoRuleViolation( - RULE_ENUM_ZERO_UNSPECIFIED, - fileName, - lineNumber, - "enum '" - + enumName - + "' zero value is '" - + name - + "'; proto3 gives an unset field the zero value, so a meaningful name there is " - + "indistinguishable from a field nobody set")); - } - } - - private void scanMessageMember( - String fileName, - String line, - int lineNumber, - String messageName, - Scan scan, - List violations) { - Matcher reservedNames = RESERVED_NAMES.matcher(line); - if (reservedNames.find()) { - Matcher quoted = QUOTED_NAME.matcher(reservedNames.group(1)); - while (quoted.find()) { - scan.reservedNames - .computeIfAbsent(messageName, key -> new LinkedHashSet<>()) - .add(quoted.group(1)); - } - return; - } - Matcher reservedNumbers = RESERVED_NUMBERS.matcher(line); - if (reservedNumbers.find()) { - Matcher number = NUMBER.matcher(reservedNumbers.group(1)); - while (number.find()) { - scan.reservedNumbers - .computeIfAbsent(messageName, key -> new LinkedHashSet<>()) - .add(Integer.valueOf(number.group())); - } - return; - } - - Matcher mapField = MAP_FIELD.matcher(line); - if (mapField.find()) { - String qualified = messageName + "." + mapField.group(1); - if (!manifest.mapAllowed(qualified)) { - violations.add( - new GrpcProtoRuleViolation( - RULE_MAP_ALLOWLIST, - fileName, - lineNumber, - "map field '" - + qualified - + "' is not on the allowlist; a map is an unversioned key space that no " - + "breaking-change check can reason about")); - } - return; - } - - Matcher field = FIELD.matcher(line); - if (!field.find()) { - return; - } - String modifier = field.group(1) == null ? "" : field.group(1).strip(); - String fieldName = field.group(3); - if (manifest.presenceRequired(messageName, fieldName) && !"optional".equals(modifier)) { - violations.add( - new GrpcProtoRuleViolation( - RULE_EXPLICIT_PRESENCE, - fileName, - lineNumber, - "field '" - + messageName - + "." - + fieldName - + "' needs presence and must be declared optional; without it, absent and " - + "default-valued are the same message on the wire")); - } - } - - private static String qualify(Deque scopeNames, String name) { - String parent = scopeNames.peek(); - return parent == null ? name : parent + "." + name; - } - - private static String unquote(String value) { - if (value == null) { - return null; - } - String stripped = value.strip(); - if (stripped.length() >= 2 && stripped.startsWith("\"") && stripped.endsWith("\"")) { - return stripped.substring(1, stripped.length() - 1); - } - return stripped; - } - - /** Everything one pass over a file collected. */ - private static final class Scan { - private String syntax; - private String protoPackage; - private int packageLine; - private final Map options = new LinkedHashMap<>(); - private final Map> reservedNumbers = new LinkedHashMap<>(); - private final Map> reservedNames = new LinkedHashMap<>(); - } -} diff --git a/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoRuleViolation.java b/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoRuleViolation.java deleted file mode 100644 index d9b7ce9..0000000 --- a/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoRuleViolation.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.grpc.contract; - -/** - * One schema rule broken, at one place. - * - *

Returned rather than thrown, and carrying a line number, because a schema review is a list. A - * validator that throws on the first violation turns "this file breaks four rules" into four - * separate runs, and the author fixes them one at a time without ever seeing the shape of the - * problem. - */ -public record GrpcProtoRuleViolation(String rule, String file, int line, String detail) { - - /** Requires a named rule, a file and a one-based line. */ - public GrpcProtoRuleViolation { - if (rule == null || rule.isBlank()) { - throw new IllegalArgumentException("a violation names the rule it broke"); - } - if (file == null || file.isBlank()) { - throw new IllegalArgumentException("a violation names the file it is in"); - } - if (detail == null || detail.isBlank()) { - throw new IllegalArgumentException("a violation explains itself"); - } - if (line < 0) { - throw new IllegalArgumentException("line must not be negative"); - } - } - - /** A violation about a whole file rather than a line in it. */ - public static GrpcProtoRuleViolation ofFile(String rule, String file, String detail) { - return new GrpcProtoRuleViolation(rule, file, 0, detail); - } - - /** {@code file:line rule — detail}, the form a build log is read in. */ - public String describe() { - return file + (line > 0 ? ":" + line : "") + " " + rule + " — " + detail; - } -} diff --git a/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoStyleManifest.java b/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoStyleManifest.java deleted file mode 100644 index 7e4040d..0000000 --- a/grpc/grpc-proto-contract/src/main/java/dev/caskeleton/grpc/contract/GrpcProtoStyleManifest.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.caskeleton.grpc.contract; - -import java.util.Map; -import java.util.Set; - -/** - * The schema rules this repository has decided on, as data rather than as prose in a review - * checklist. - * - *

Three of the five fields are allowlists, and that shape is the decision: {@code Any}, {@code - * Struct} and {@code map} are not banned, they are things you have to ask for by name. A ban gets - * worked around; an allowlist entry gets read by the next person to open the manifest and carries - * the field it was granted for. - */ -public record GrpcProtoStyleManifest( - String organization, - Set handWrittenJavaPackages, - Set wellKnownTypeAllowlist, - Set mapFieldAllowlist, - Map> presenceRequiredFields) { - - /** The well-known types every schema may use without asking. */ - private static final Set ALWAYS_ALLOWED_WELL_KNOWN_TYPES = - Set.of( - "google/protobuf/timestamp.proto", - "google/protobuf/duration.proto", - "google/protobuf/field_mask.proto", - "google/protobuf/empty.proto", - "google/protobuf/wrappers.proto"); - - /** Copies every collection so a manifest cannot widen after it has been reviewed. */ - public GrpcProtoStyleManifest { - if (organization == null || organization.isBlank()) { - throw new IllegalArgumentException("a style manifest names the owning organization"); - } - if (handWrittenJavaPackages == null - || wellKnownTypeAllowlist == null - || mapFieldAllowlist == null - || presenceRequiredFields == null) { - throw new IllegalArgumentException("every manifest allowlist must be present"); - } - handWrittenJavaPackages = Set.copyOf(handWrittenJavaPackages); - wellKnownTypeAllowlist = Set.copyOf(wellKnownTypeAllowlist); - mapFieldAllowlist = Set.copyOf(mapFieldAllowlist); - presenceRequiredFields = - presenceRequiredFields.entrySet().stream() - .collect( - java.util.stream.Collectors.toUnmodifiableMap( - Map.Entry::getKey, entry -> Set.copyOf(entry.getValue()))); - } - - /** - * This repository's manifest. - * - *

The hand-written package is {@code dev.caskeleton.grpc}: generated code must land somewhere - * else, because a generated class and a hand-written one in the same package are - * indistinguishable to a reader and the generated one gets edited exactly once before somebody - * regenerates. - */ - public static GrpcProtoStyleManifest caSkeleton() { - return new GrpcProtoStyleManifest( - "hyeonworks", - Set.of("dev.caskeleton"), - ALWAYS_ALLOWED_WELL_KNOWN_TYPES, - Set.of(), - Map.of()); - } - - /** Whether {@code importPath} may be imported. */ - public boolean wellKnownTypeAllowed(String importPath) { - return !importPath.startsWith("google/protobuf/") - || wellKnownTypeAllowlist.contains(importPath); - } - - /** Whether a {@code map} field is allowed at {@code message.field}. */ - public boolean mapAllowed(String qualifiedField) { - return mapFieldAllowlist.contains(qualifiedField); - } - - /** Whether {@code field} of {@code message} must be declared {@code optional}. */ - public boolean presenceRequired(String message, String field) { - return presenceRequiredFields.getOrDefault(message, Set.of()).contains(field); - } - - /** A copy of this manifest that also allows the given well-known type imports. */ - public GrpcProtoStyleManifest allowingWellKnownTypes(Set additionalImports) { - java.util.Set widened = new java.util.LinkedHashSet<>(wellKnownTypeAllowlist); - widened.addAll(additionalImports); - return new GrpcProtoStyleManifest( - organization, handWrittenJavaPackages, widened, mapFieldAllowlist, presenceRequiredFields); - } - - /** A copy of this manifest that also allows the given {@code message.field} map fields. */ - public GrpcProtoStyleManifest allowingMapFields(Set qualifiedFields) { - java.util.Set widened = new java.util.LinkedHashSet<>(mapFieldAllowlist); - widened.addAll(qualifiedFields); - return new GrpcProtoStyleManifest( - organization, - handWrittenJavaPackages, - wellKnownTypeAllowlist, - widened, - presenceRequiredFields); - } - - /** A copy of this manifest that also requires explicit presence on the given fields. */ - public GrpcProtoStyleManifest requiringPresence(String message, Set fields) { - java.util.Map> widened = - new java.util.LinkedHashMap<>(presenceRequiredFields); - widened.merge( - message, - Set.copyOf(fields), - (existing, added) -> { - java.util.Set merged = new java.util.LinkedHashSet<>(existing); - merged.addAll(added); - return merged; - }); - return new GrpcProtoStyleManifest( - organization, handWrittenJavaPackages, wellKnownTypeAllowlist, mapFieldAllowlist, widened); - } -} diff --git a/grpc/grpc-proto-contract/src/main/resources/proto/buf.gen.yaml b/grpc/grpc-proto-contract/src/main/resources/proto/buf.gen.yaml deleted file mode 100644 index a357d27..0000000 --- a/grpc/grpc-proto-contract/src/main/resources/proto/buf.gen.yaml +++ /dev/null @@ -1,23 +0,0 @@ -# What a Buf-driven generation would emit, recorded even though this build does not run it. -# -# No protoc runs here (ADR-GRPC-002), so this file is a specification rather than a step. It exists -# because the three decisions it encodes are the ones GrpcCodegenManifest enforces from Java, and a -# reader who wants to know what "the single codegen owner produces" means should find one answer -# rather than two: -# -# - generated Java lands under build/, never in a source tree; -# - the generated package is disjoint from the hand-written dev.caskeleton root; -# - plugin versions come from the managed platform, so no version literal appears below. -version: v2 -managed: - enabled: true - override: - - file_option: java_multiple_files - value: true - - file_option: java_package_suffix - value: generated -plugins: - - remote: buf.build/protocolbuffers/java - out: build/generated/source/proto/main/java - - remote: buf.build/grpc/java - out: build/generated/source/proto/main/grpc diff --git a/grpc/grpc-proto-contract/src/main/resources/proto/buf.lock b/grpc/grpc-proto-contract/src/main/resources/proto/buf.lock deleted file mode 100644 index dc72df5..0000000 --- a/grpc/grpc-proto-contract/src/main/resources/proto/buf.lock +++ /dev/null @@ -1,11 +0,0 @@ -# Buf dependency lock. -# -# Empty by design: the Stable schema imports nothing outside itself. The well-known types this -# platform allows (timestamp, duration, field_mask, empty, wrappers) ship with protoc rather than -# coming from a Buf module, and GrpcProtoStyleManifest refuses any other google.protobuf import -# without an explicit allowlist entry. -# -# The file is committed rather than omitted so that adding a first dependency is a visible diff in a -# file that already exists, instead of a new file nobody reviews. -version: v2 -deps: [] diff --git a/grpc/grpc-proto-contract/src/main/resources/proto/buf.yaml b/grpc/grpc-proto-contract/src/main/resources/proto/buf.yaml deleted file mode 100644 index 22b2a1d..0000000 --- a/grpc/grpc-proto-contract/src/main/resources/proto/buf.yaml +++ /dev/null @@ -1,18 +0,0 @@ -# Buf module configuration for the Stable schema. -# -# The rules named here are also implemented in GrpcProtoContractValidator, which is what actually -# fails this repository's build: the Buf CLI is not part of this toolchain, and a gate that silently -# passes when a binary is missing is worse than one that computes the same judgement from the -# committed schema. This file stays accurate so that running `buf lint` / `buf breaking` in an -# environment that has the CLI reaches the same verdict. -version: v2 -modules: - - path: . -lint: - use: - - STANDARD -breaking: - # FILE, not WIRE or WIRE_JSON. Wire compatibility alone would let a field rename or a Java package - # move through as "compatible" while every generated consumer stops compiling. - use: - - FILE diff --git a/grpc/grpc-proto-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcProtoContractValidatorTest.java b/grpc/grpc-proto-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcProtoContractValidatorTest.java deleted file mode 100644 index 6d19090..0000000 --- a/grpc/grpc-proto-contract/src/test/java/dev/caskeleton/grpc/contract/GrpcProtoContractValidatorTest.java +++ /dev/null @@ -1,324 +0,0 @@ -package dev.caskeleton.grpc.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -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 GrpcProtoContractValidatorTest { - - private final GrpcProtoContractValidator validator = - new GrpcProtoContractValidator(GrpcProtoStyleManifest.caSkeleton()); - - private static String committedSchema(String resourcePath) { - try (InputStream stream = - GrpcProtoContractValidatorTest.class.getClassLoader().getResourceAsStream(resourcePath)) { - if (stream == null) { - throw new IllegalStateException("missing committed schema resource: " + resourcePath); - } - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - @Test - @DisplayName("the committed Stable schema passes every style rule") - void committedSchemaIsCompliant() { - List files = - List.of( - "proto/hyeonworks/grpc/common/v1/error.proto", - "proto/hyeonworks/grpc/common/v1/stream.proto"); - - for (String file : files) { - List violations = validator.validate(file, committedSchema(file)); - assertThat(violations) - .describedAs( - "violations in %s: %s", - file, violations.stream().map(GrpcProtoRuleViolation::describe).toList()) - .isEmpty(); - } - } - - @Test - @DisplayName("the committed Buf configuration states the same rules the validator enforces") - void theBufConfigurationAgreesWithTheValidator() { - String bufYaml = committedSchema("proto/buf.yaml"); - String bufGen = committedSchema("proto/buf.gen.yaml"); - String bufLock = committedSchema("proto/buf.lock"); - - // FILE, not WIRE: the category the Stable gate is fixed at. - assertThat(bufYaml).contains("use:").contains("- FILE").contains("- STANDARD"); - // Generation lands under build/ and into a package the hand-written root does not occupy. - assertThat(bufGen) - .contains("build/generated/source/proto/main/java") - .contains("build/generated/source/proto/main/grpc") - .contains("java_package_suffix") - // Never into a source tree: generated code that lands in src/ gets committed and then - // edited. The prose above the plugins block names dev.caskeleton as the package to stay out - // of, so the check is on the emitted paths rather than on the word. - .doesNotContain("out: src/"); - // No version literal: the managed platform owns plugin versions. - assertThat(bufGen).doesNotContain("version: v1"); - assertThat(bufLock).contains("deps: []"); - } - - @Test - @DisplayName("proto2 source is refused") - void proto2SourceIsRefused() { - String source = - """ - syntax = "proto2"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - """; - - assertThat(validator.validate("legacy.proto", source)) - .extracting(GrpcProtoRuleViolation::rule) - .contains(GrpcProtoContractValidator.RULE_PROTO3_SYNTAX); - } - - @Test - @DisplayName("an unversioned package is refused") - void unversionedPackageIsRefused() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document; - option java_multiple_files = true; - option java_package = "hyeonworks.document.generated"; - """; - - assertThat(validator.validate("document.proto", source)) - .extracting(GrpcProtoRuleViolation::rule) - .contains(GrpcProtoContractValidator.RULE_PACKAGE_VERSIONED); - } - - @Test - @DisplayName("a generated java_package inside a hand-written package is refused") - void generatedPackageMayNotCollideWithHandWrittenCode() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "dev.caskeleton.grpc.document"; - """; - - assertThat(validator.validate("document.proto", source)) - .extracting(GrpcProtoRuleViolation::rule) - .contains(GrpcProtoContractValidator.RULE_JAVA_PACKAGE_SEPARATE); - } - - @Test - @DisplayName("a missing java_multiple_files option is refused") - void javaMultipleFilesIsRequired() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_package = "hyeonworks.document.v1.generated"; - """; - - assertThat(validator.validate("document.proto", source)) - .extracting(GrpcProtoRuleViolation::rule) - .contains(GrpcProtoContractValidator.RULE_JAVA_MULTIPLE_FILES); - } - - @Test - @DisplayName("an enum zero value without the _UNSPECIFIED suffix is refused, with its line") - void enumZeroValueNeedsTheUnspecifiedSuffix() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - - enum DocumentState { - DRAFT = 0; - PUBLISHED = 1; - } - """; - - List violations = validator.validate("document.proto", source); - - assertThat(violations) - .singleElement() - .satisfies( - violation -> { - assertThat(violation.rule()) - .isEqualTo(GrpcProtoContractValidator.RULE_ENUM_ZERO_UNSPECIFIED); - assertThat(violation.line()).isEqualTo(7); - assertThat(violation.detail()).contains("DocumentState").contains("DRAFT"); - }); - } - - @Test - @DisplayName("a removed field number that is not reserved fails, and reserving it passes") - void removedFieldNumbersMustStayReserved() { - String withoutReserved = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - - message Document { - string id = 1; - string title = 4; - } - """; - GrpcProtoContractValidator.SchemaHistory history = - new GrpcProtoContractValidator.SchemaHistory( - Map.of("Document", Set.of(2, 3)), Map.of("Document", Set.of("legacy_body"))); - - assertThat(validator.validate("document.proto", withoutReserved, history)) - .extracting(GrpcProtoRuleViolation::rule) - .containsOnly(GrpcProtoContractValidator.RULE_RESERVED_HISTORY); - - String withReserved = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - - message Document { - reserved 2, 3; - reserved "legacy_body"; - string id = 1; - string title = 4; - } - """; - - assertThat(validator.validate("document.proto", withReserved, history)).isEmpty(); - } - - @Test - @DisplayName("Any and Struct need an explicit allowlist entry; Timestamp does not") - void anyAndStructAreAllowlistedByName() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - import "google/protobuf/timestamp.proto"; - import "google/protobuf/any.proto"; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - """; - - assertThat(validator.validate("document.proto", source)) - .singleElement() - .satisfies( - violation -> { - assertThat(violation.rule()) - .isEqualTo(GrpcProtoContractValidator.RULE_WELL_KNOWN_TYPE_ALLOWLIST); - assertThat(violation.detail()).contains("google/protobuf/any.proto"); - }); - - GrpcProtoContractValidator widened = - new GrpcProtoContractValidator( - GrpcProtoStyleManifest.caSkeleton() - .allowingWellKnownTypes(Set.of("google/protobuf/any.proto"))); - assertThat(widened.validate("document.proto", source)).isEmpty(); - } - - @Test - @DisplayName("a map field needs an allowlist entry naming the message and field") - void mapFieldsAreAllowlistedByName() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - - message Document { - map labels = 1; - } - """; - - assertThat(validator.validate("document.proto", source)) - .extracting(GrpcProtoRuleViolation::rule) - .containsOnly(GrpcProtoContractValidator.RULE_MAP_ALLOWLIST); - - GrpcProtoContractValidator widened = - new GrpcProtoContractValidator( - GrpcProtoStyleManifest.caSkeleton().allowingMapFields(Set.of("Document.labels"))); - assertThat(widened.validate("document.proto", source)).isEmpty(); - } - - @Test - @DisplayName("a presence-required field must be declared optional") - void presenceRequiredFieldsMustBeOptional() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - - message Document { - string id = 1; - string title = 2; - } - """; - GrpcProtoContractValidator strict = - new GrpcProtoContractValidator( - GrpcProtoStyleManifest.caSkeleton().requiringPresence("Document", Set.of("title"))); - - assertThat(strict.validate("document.proto", source)) - .singleElement() - .satisfies( - violation -> { - assertThat(violation.rule()) - .isEqualTo(GrpcProtoContractValidator.RULE_EXPLICIT_PRESENCE); - assertThat(violation.detail()).contains("Document.title"); - }); - - String withOptional = source.replace(" string title = 2;", " optional string title = 2;"); - assertThat(strict.validate("document.proto", withOptional)).isEmpty(); - } - - @Test - @DisplayName("nested messages are qualified, so a rule names the type it means") - void nestedMessagesAreQualified() { - String source = - """ - syntax = "proto3"; - package hyeonworks.document.v1; - option java_multiple_files = true; - option java_package = "hyeonworks.document.v1.generated"; - - message Outer { - message Inner { - map labels = 1; - } - } - """; - - assertThat(validator.validate("document.proto", source)) - .singleElement() - .satisfies(violation -> assertThat(violation.detail()).contains("Outer.Inner.labels")); - } - - @Test - @DisplayName("a violation renders as file:line rule — detail") - void violationRendersForABuildLog() { - GrpcProtoRuleViolation violation = - new GrpcProtoRuleViolation("RULE_X", "document.proto", 12, "something is wrong"); - - assertThat(violation.describe()).isEqualTo("document.proto:12 RULE_X — something is wrong"); - assertThat(GrpcProtoRuleViolation.ofFile("RULE_Y", "document.proto", "whole file").describe()) - .isEqualTo("document.proto RULE_Y — whole file"); - } -} diff --git a/grpc/grpc-runtime/build.gradle b/grpc/grpc-runtime/build.gradle new file mode 100644 index 0000000..350747d --- /dev/null +++ b/grpc/grpc-runtime/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'ca.grpc-platform-module' +} + +// The Stable runtime: one leaf for one dependency boundary (io.grpc api/stub). +// +// policy validation, context propagation, status/rich-error mapping, TLS/credential profiles, +// deadline and cancellation, retry ownership, idempotency and completion recovery, +// server streaming, payload size and compression +// server the typed service adapter SPI, the interceptor order contract, and the Netty +// server/executor/admission profiles (configuration models, not Netty wiring) +// client named channel profiles, channel runtime generations with drain, the typed stub +// factory that refuses to hand a raw Channel to application code +// discovery Static/DNS resolvers, pick_first/round_robin, Kubernetes routing profiles +// admin health registry, reflection exposure policy, drain coordinator, policy snapshot +// +// These were five leaves until 2026-09-28; they shared one framework boundary and depended on each +// other in a line, so the split bought no enforceable rule. Package names were kept so no import +// changed. Real Netty lives in `grpc-testkit`'s certification lanes. + +dependencies { + api project(':grpc:grpc-core-api') + + // api: interceptors, context binders, the error mapper and the stub factory name io.grpc types + // in public signatures, so an adopter cannot compile against this module without them. + api "io.grpc:grpc-api" + api "io.grpc:grpc-stub" + + // The shared operation-ledger fake, held to the same contract as the JPA adapter. + testImplementation testFixtures(project(':grpc:grpc-core-api')) +} diff --git a/grpc-advanced/grpc-advanced-resilience/gradle.lockfile b/grpc/grpc-runtime/gradle.lockfile similarity index 100% rename from grpc-advanced/grpc-advanced-resilience/gradle.lockfile rename to grpc/grpc-runtime/gradle.lockfile diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcAdminExposurePolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcAdminExposurePolicy.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcAdminExposurePolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcAdminExposurePolicy.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinator.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinator.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPhase.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPhase.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPhase.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPhase.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPolicy.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainPolicy.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainResult.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainResult.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainResult.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcDrainResult.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthPolicy.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthPolicy.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthState.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthState.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthState.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcHealthState.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshot.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshot.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshot.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshot.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotService.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotService.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotService.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotService.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionAccessDecision.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionAccessDecision.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionAccessDecision.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionAccessDecision.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionMode.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionMode.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionMode.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionMode.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicy.java similarity index 100% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicy.java diff --git a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistry.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistry.java similarity index 90% rename from grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistry.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistry.java index ee4ad40..4be13bd 100644 --- a/grpc/grpc-admin/src/main/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistry.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistry.java @@ -22,7 +22,9 @@ public final class GrpcServiceHealthRegistry { private final ConcurrentMap states = new ConcurrentHashMap<>(); private final ConcurrentMap dependencyHealth = new ConcurrentHashMap<>(); private final GrpcHealthPolicy policy; - private volatile boolean draining; + // Every write holds this registry's lock, so a state change cannot land between the draining + // check and its write and undo a drain that started in between. + private boolean draining; /** Binds a registry to its health policy. */ public GrpcServiceHealthRegistry(GrpcHealthPolicy policy) { @@ -34,7 +36,7 @@ public final class GrpcServiceHealthRegistry { } /** Registers a service, unknown until something says otherwise. */ - public void register(String serviceName) { + public synchronized void register(String serviceName) { requireServiceName(serviceName); states.putIfAbsent(serviceName, GrpcHealthState.UNKNOWN); } @@ -45,7 +47,7 @@ public final class GrpcServiceHealthRegistry { *

Ignored while draining: a service that reports itself healthy after the drain has started * would be routed traffic the instance has already promised not to take. */ - public void markServing(String serviceName) { + public synchronized void markServing(String serviceName) { requireServiceName(serviceName); if (draining) { return; @@ -55,7 +57,7 @@ public final class GrpcServiceHealthRegistry { } /** Records that a service is not serving. */ - public void markNotServing(String serviceName) { + public synchronized void markNotServing(String serviceName) { requireServiceName(serviceName); if (draining) { return; @@ -65,7 +67,7 @@ public final class GrpcServiceHealthRegistry { } /** Records a dependency's health, which only matters when the policy says it does. */ - public void recordDependencyHealth(String dependencyName, boolean healthy) { + public synchronized void recordDependencyHealth(String dependencyName, boolean healthy) { if (dependencyName == null || dependencyName.isBlank()) { throw new IllegalArgumentException("a dependency needs a name"); } @@ -81,7 +83,7 @@ public final class GrpcServiceHealthRegistry { *

Called first in a shutdown, before admission stops, so that a load balancer has a chance to * stop sending before the server starts refusing. */ - public void beginDraining() { + public synchronized void beginDraining() { draining = true; states.replaceAll((service, state) -> GrpcHealthState.DRAINING); } diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcCallCredentialProvider.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcCallCredentialProvider.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcCallCredentialProvider.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcCallCredentialProvider.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelDrainPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelDrainPolicy.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelDrainPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelDrainPolicy.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelGeneration.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelGeneration.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelGeneration.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelGeneration.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelProfileValidator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelProfileValidator.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelProfileValidator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelProfileValidator.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntime.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntime.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntime.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntime.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistry.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistry.java similarity index 86% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistry.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistry.java index b25dec2..188ad5f 100644 --- a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistry.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistry.java @@ -3,7 +3,9 @@ package dev.caskeleton.grpc.client; import dev.caskeleton.grpc.core.GrpcChannelProfileName; import java.time.Instant; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -24,8 +26,9 @@ public final class GrpcChannelRuntimeRegistry { private final ConcurrentMap> current = new ConcurrentHashMap<>(); - private final ConcurrentMap> draining = - new ConcurrentHashMap<>(); + // Guarded by this registry's lock, like every swap: rotations are rare, and one lock keeps the + // current pointer and the draining list from disagreeing. + private final Map> draining = new HashMap<>(); private final GrpcChannelDrainPolicy drainPolicy; /** Binds a registry to the drain policy its swaps use. */ @@ -37,7 +40,7 @@ public final class GrpcChannelRuntimeRegistry { } /** Installs the first generation for a profile. */ - public GrpcChannelRuntime install(GrpcChannelGeneration generation) { + public synchronized GrpcChannelRuntime install(GrpcChannelGeneration generation) { if (generation == null) { throw new IllegalArgumentException("a generation is required"); } @@ -80,7 +83,7 @@ public final class GrpcChannelRuntimeRegistry { * * @throws IllegalArgumentException when {@code next} does not supersede what is installed */ - public GrpcChannelRuntime rotate(GrpcChannelGeneration next, Instant now) { + public synchronized GrpcChannelRuntime rotate(GrpcChannelGeneration next, Instant now) { if (next == null || now == null) { throw new IllegalArgumentException("a rotation needs a generation and a moment"); } @@ -102,15 +105,12 @@ public final class GrpcChannelRuntimeRegistry { GrpcChannelRuntime replacement = new GrpcChannelRuntime(next); holder.set(replacement); previous.beginDrain(); - draining - .computeIfAbsent( - next.profileName(), key -> java.util.Collections.synchronizedList(new ArrayList<>())) - .add(previous); + draining.computeIfAbsent(next.profileName(), key -> new ArrayList<>()).add(previous); return replacement; } /** The generations still draining for a profile. */ - public List draining(GrpcChannelProfileName profileName) { + public synchronized List draining(GrpcChannelProfileName profileName) { return List.copyOf(draining.getOrDefault(profileName, List.of())); } @@ -119,7 +119,7 @@ public final class GrpcChannelRuntimeRegistry { * * @return how many were retired */ - public int retireQuiescent(GrpcChannelProfileName profileName) { + public synchronized int retireQuiescent(GrpcChannelProfileName profileName) { List runtimes = draining.get(profileName); if (runtimes == null) { return 0; diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcClientCallContext.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcClientCallContext.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcClientCallContext.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcClientCallContext.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicy.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicy.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcLoadBalancingPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcLoadBalancingPolicy.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcLoadBalancingPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcLoadBalancingPolicy.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfile.java similarity index 93% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfile.java index 959d2f4..1a2075a 100644 --- a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfile.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfile.java @@ -1,5 +1,6 @@ package dev.caskeleton.grpc.client; +import dev.caskeleton.grpc.api.policy.GrpcTransportLimits; import dev.caskeleton.grpc.core.GrpcChannelProfileName; import dev.caskeleton.grpc.resilience.GrpcRetryOwner; import dev.caskeleton.grpc.security.GrpcTlsProfile; @@ -77,8 +78,8 @@ public record GrpcNamedChannelProfile( GrpcLoadBalancingPolicy.PICK_FIRST, retryOwner, tls, - 1024L * 1024L, - 8192, + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, Duration.ofSeconds(30), false); } @@ -92,8 +93,8 @@ public record GrpcNamedChannelProfile( GrpcLoadBalancingPolicy.ROUND_ROBIN, retryOwner, tls, - 1024L * 1024L, - 8192, + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, Duration.ofSeconds(30), false); } diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcStubDescriptor.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcStubDescriptor.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcStubDescriptor.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcStubDescriptor.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcStubPolicyApplier.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcStubPolicyApplier.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcStubPolicyApplier.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcStubPolicyApplier.java diff --git a/grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcTypedStubFactory.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcTypedStubFactory.java similarity index 100% rename from grpc/grpc-client/src/main/java/dev/caskeleton/grpc/client/GrpcTypedStubFactory.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/client/GrpcTypedStubFactory.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/context/GrpcContextBinder.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/context/GrpcContextBinder.java similarity index 92% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/context/GrpcContextBinder.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/context/GrpcContextBinder.java index 5f0f67c..5eef3bd 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/context/GrpcContextBinder.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/context/GrpcContextBinder.java @@ -87,15 +87,14 @@ public final class GrpcContextBinder { if (work == null) { throw new IllegalArgumentException("work must not be null"); } - GrpcContextSnapshot captured = SNAPSHOT.get(); - if (captured == null && policy.failClosedWithoutContext()) { + // The whole io.grpc Context, not just the snapshot value: it also carries the call's + // cancellation and deadline, which the other thread must see. + Context captured = Context.current(); + if (SNAPSHOT.get(captured) == null && policy.failClosedWithoutContext()) { throw new IllegalStateException( "refusing to hand work to another thread with no call context to carry"); } - if (captured == null) { - return work; - } - return () -> runWith(captured, work); + return captured.wrap(work); } /** An {@link Executor} that carries the submitting thread's context to every task. */ diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/context/GrpcContextPropagationPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/context/GrpcContextPropagationPolicy.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/context/GrpcContextPropagationPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/context/GrpcContextPropagationPolicy.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/context/GrpcContextSnapshot.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/context/GrpcContextSnapshot.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/context/GrpcContextSnapshot.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/context/GrpcContextSnapshot.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellableOperation.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellableOperation.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellableOperation.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellableOperation.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinator.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinator.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationReason.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationReason.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationReason.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcCancellationReason.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculator.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculator.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlinePolicyValidator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlinePolicyValidator.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlinePolicyValidator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcDeadlinePolicyValidator.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcDependencyBudget.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcDependencyBudget.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/deadline/GrpcDependencyBudget.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/deadline/GrpcDependencyBudget.java diff --git a/grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidator.java similarity index 100% rename from grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidator.java diff --git a/grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfile.java similarity index 100% rename from grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfile.java diff --git a/grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileValidator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileValidator.java similarity index 100% rename from grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileValidator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileValidator.java diff --git a/grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesRoutingMode.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesRoutingMode.java similarity index 100% rename from grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesRoutingMode.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcKubernetesRoutingMode.java diff --git a/grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverProfile.java similarity index 100% rename from grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverProfile.java diff --git a/grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverType.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverType.java similarity index 100% rename from grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverType.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcResolverType.java diff --git a/grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcStableLoadBalancer.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcStableLoadBalancer.java similarity index 100% rename from grpc/grpc-discovery/src/main/java/dev/caskeleton/grpc/discovery/GrpcStableLoadBalancer.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/discovery/GrpcStableLoadBalancer.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcErrorExposurePolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcErrorExposurePolicy.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcErrorExposurePolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcErrorExposurePolicy.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcErrorMapper.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcErrorMapper.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcErrorMapper.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcErrorMapper.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcRichErrorDetail.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcRichErrorDetail.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcRichErrorDetail.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcRichErrorDetail.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcStatusMapping.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcStatusMapping.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/error/GrpcStatusMapping.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/error/GrpcStatusMapping.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconciler.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconciler.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconciler.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconciler.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionResolution.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionResolution.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionResolution.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcCompletionResolution.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java similarity index 93% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java index 7307ed4..e232669 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java @@ -106,12 +106,16 @@ public final class GrpcIdempotencyInterceptor { + identity.storageKey() + "' has no outcome reference to replay"))); } - if (record.state() == GrpcOperationLedgerState.FAILED_TERMINAL) { + if (record.state() == GrpcOperationLedgerState.FAILED_TERMINAL + && ledger.reclaimFailed(identity, requestFingerprint, now)) { // A terminal failure is not replayed: the caller asked for the operation, it did not happen, - // and repeating it is exactly what the key makes safe. + // and repeating it is exactly what the key makes safe — but only for the one retry that + // re-claims the row. Proceeding unclaimed runs concurrent retries twice and leaves the + // commit without an owner. return GrpcIdempotencyDecision.proceed( - "the previous attempt failed terminally; the key makes repeating it safe"); + "the previous attempt failed terminally; this caller re-claimed it for a new attempt"); } + // Running, or a failed attempt another retry re-claimed first. return waitForInProgress ? GrpcIdempotencyDecision.waitAndPoll(inProgressPollInterval) : GrpcIdempotencyDecision.rejectInProgress(); diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatus.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatus.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatus.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatus.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatusQuery.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatusQuery.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatusQuery.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationStatusQuery.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplay.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplay.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplay.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplay.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcRequestFingerprint.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcRequestFingerprint.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcRequestFingerprint.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcRequestFingerprint.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcCompressionProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcCompressionProfile.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcCompressionProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcCompressionProfile.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcMessageSizeProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcMessageSizeProfile.java similarity index 85% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcMessageSizeProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcMessageSizeProfile.java index 28fd2de..6b7c503 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcMessageSizeProfile.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcMessageSizeProfile.java @@ -1,5 +1,7 @@ package dev.caskeleton.grpc.policy; +import dev.caskeleton.grpc.api.policy.GrpcTransportLimits; + /** * A method's size bounds, chosen rather than inherited. * @@ -40,7 +42,13 @@ public record GrpcMessageSizeProfile( /** The Stable default for an ordinary RPC: 1 MiB messages, no compression. */ public static GrpcMessageSizeProfile standard() { return new GrpcMessageSizeProfile( - 1024L * 1024L, 1024L * 1024L, 8192L, 1000, 8192, 8, GrpcCompressionProfile.IDENTITY); + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, + 1000, + 8192, + 8, + GrpcCompressionProfile.IDENTITY); } /** An explicitly reviewed large-message profile: 8 MiB, gzip. */ @@ -48,7 +56,7 @@ public record GrpcMessageSizeProfile( return new GrpcMessageSizeProfile( 8L * 1024L * 1024L, 8L * 1024L * 1024L, - 8192L, + GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, 10_000, 65_536, 12, diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicy.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicy.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcSizeViolation.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcSizeViolation.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/policy/GrpcSizeViolation.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/policy/GrpcSizeViolation.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcMethodRetryConfig.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcMethodRetryConfig.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcMethodRetryConfig.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcMethodRetryConfig.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryBudget.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryBudget.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryBudget.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryBudget.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryCoordinator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryCoordinator.java similarity index 95% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryCoordinator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryCoordinator.java index b967e90..5da90b5 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryCoordinator.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryCoordinator.java @@ -78,13 +78,15 @@ public final class GrpcRetryCoordinator { } Duration backoff = jittered(config.backoffBefore(completedAttempt + 1), config.jitterFactor()); - if (remaining.remaining().compareTo(backoff) <= 0) { + // Read once: the budget is live, and a second read could fall below the backoff. + Duration left = remaining.remaining(); + if (left.compareTo(backoff) <= 0) { return GrpcRetryDecision.refuse( GrpcRetryDecision.Verdict.TERMINAL, "the remaining deadline is shorter than the backoff, so a retry could not finish"); } GrpcDeadlineBudget afterBackoff = - new GrpcDeadlineBudget(remaining.remaining().minus(backoff), remaining.profile()); + new GrpcDeadlineBudget(left.minus(backoff), remaining.profile()); if (!afterBackoff.canStartDependencyCall()) { return GrpcRetryDecision.refuse( GrpcRetryDecision.Verdict.TERMINAL, diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryDecision.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryDecision.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryDecision.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryDecision.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibility.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibility.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibility.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibility.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwner.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwner.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwner.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwner.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidator.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidator.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcServiceConfigPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcServiceConfigPolicy.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcServiceConfigPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcServiceConfigPolicy.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyDecision.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyDecision.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyDecision.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyDecision.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyProfile.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyProfile.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidator.java similarity index 89% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidator.java index f41151d..6becd96 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidator.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidator.java @@ -35,7 +35,9 @@ public final class GrpcWaitForReadyValidator { + policy.method().canonical() + "' must carry one"); } - if (remaining.expired()) { + // Read once: the budget is live and keeps shrinking between reads. + Duration left = remaining.remaining(); + if (left.isZero()) { return GrpcWaitForReadyDecision.failFast("no deadline remains to queue inside"); } if (policy.waitForReady() != profile.policy()) { @@ -47,9 +49,7 @@ public final class GrpcWaitForReadyValidator { + "; the stricter of the two wins"); } Duration allowance = - profile.maxQueueWait().compareTo(remaining.remaining()) <= 0 - ? profile.maxQueueWait() - : remaining.remaining(); + profile.maxQueueWait().compareTo(left) <= 0 ? profile.maxQueueWait() : left; return GrpcWaitForReadyDecision.queueFor( allowance, "queueing under " + profile.policy() + " within the queue budget"); } diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcAuthenticationProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcAuthenticationProfile.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcAuthenticationProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcAuthenticationProfile.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialGeneration.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialGeneration.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialGeneration.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialGeneration.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManager.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManager.java similarity index 64% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManager.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManager.java index bcf033f..69991cf 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManager.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManager.java @@ -86,22 +86,29 @@ public final class GrpcCredentialRotationManager { if (next == null || now == null) { throw new IllegalArgumentException("a rotation needs a generation and a moment"); } - State observed = state.get(); - if (observed.current().generation() == next.generation()) { - // Idempotent: re-applying the generation that is already current is a no-op rather than a - // second drain, because a retried rotation must not cancel the calls the first one admitted. - return new RotationPlan(observed.current(), Optional.empty(), Optional.empty()); - } - if (!observed.current().supersededBy(next)) { - throw new IllegalArgumentException( - "credential generation " - + next.generation() - + " does not supersede the current generation " - + observed.current().generation()); - } Instant deadline = now.plus(drainWindow); - state.set(new State(next, observed.current(), deadline)); - return new RotationPlan(next, Optional.of(observed.current()), Optional.of(deadline)); + // Compare-and-set loop: a racing rotator or completeDrain re-runs the checks against the state + // it actually replaces, so a rotation never goes backwards and never loses a draining + // generation. + while (true) { + State observed = state.get(); + if (observed.current().generation() == next.generation()) { + // Idempotent: re-applying the generation that is already current is a no-op rather than a + // second drain, because a retried rotation must not cancel the calls the first one + // admitted. + return new RotationPlan(observed.current(), Optional.empty(), Optional.empty()); + } + if (!observed.current().supersededBy(next)) { + throw new IllegalArgumentException( + "credential generation " + + next.generation() + + " does not supersede the current generation " + + observed.current().generation()); + } + if (state.compareAndSet(observed, new State(next, observed.current(), deadline))) { + return new RotationPlan(next, Optional.of(observed.current()), Optional.of(deadline)); + } + } } /** @@ -114,9 +121,28 @@ public final class GrpcCredentialRotationManager { return observed.drainDeadline() != null && !now.isBefore(observed.drainDeadline()); } - /** Forgets the draining generation once its work has finished or been cancelled. */ - public void completeDrain() { - State observed = state.get(); - state.set(new State(observed.current(), null, null)); + /** + * Forgets {@code drained} once its work has finished or been cancelled. + * + *

Names the generation because a drain completes asynchronously: by the time the caller that + * drained generation N reports back, a later rotation may already be draining N+1, and clearing + * "whatever is draining now" would end that newer drain before its calls finished. + * + * @return whether {@code drained} was the draining generation and has now been forgotten; false + * when a later rotation already replaced it + */ + public boolean completeDrain(GrpcCredentialGeneration drained) { + if (drained == null) { + throw new IllegalArgumentException("a completed drain names the generation it drained"); + } + while (true) { + State observed = state.get(); + if (observed.draining() == null || observed.draining().generation() != drained.generation()) { + return false; + } + if (state.compareAndSet(observed, new State(observed.current(), null, null))) { + return true; + } + } } } diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcTlsProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcTlsProfile.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcTlsProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/security/GrpcTlsProfile.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java similarity index 66% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java index c25f67a..a6b346c 100644 --- a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java @@ -1,7 +1,5 @@ package dev.caskeleton.grpc.server; -import java.util.concurrent.atomic.AtomicInteger; - /** * Refuses work the server cannot do, before it spends anything on it. * @@ -14,9 +12,12 @@ public final class GrpcAdmissionController { private final int maxConcurrentCalls; private final int maxQueuedCalls; - private final AtomicInteger inFlight = new AtomicInteger(); - private final AtomicInteger queued = new AtomicInteger(); - private final AtomicInteger rejected = new AtomicInteger(); + + // One lock for both counters: every decision reads one and changes the other, and a check on an + // atomic followed by an increment lets racing callers all pass the same check. + private int inFlight; + private int queued; + private int rejected; /** Bounds concurrency and queueing separately. */ public GrpcAdmissionController(int maxConcurrentCalls, int maxQueuedCalls) { @@ -48,56 +49,54 @@ public final class GrpcAdmissionController { } /** Admits a call, queues it, or refuses it. */ - public Decision tryAdmit() { - int running = inFlight.get(); - if (running < maxConcurrentCalls) { - inFlight.incrementAndGet(); - return new Decision(true, inFlight.get(), queued.get(), "within the concurrency bound"); + public synchronized Decision tryAdmit() { + if (inFlight < maxConcurrentCalls) { + inFlight++; + return new Decision(true, inFlight, queued, "within the concurrency bound"); } - int waiting = queued.get(); - if (waiting < maxQueuedCalls) { - queued.incrementAndGet(); - return new Decision(true, running, queued.get(), "queued within the admission bound"); + if (queued < maxQueuedCalls) { + queued++; + return new Decision(true, inFlight, queued, "queued within the admission bound"); } - rejected.incrementAndGet(); + rejected++; return new Decision( false, - running, - waiting, + inFlight, + queued, "at capacity: " - + running + + inFlight + " in flight and " - + waiting + + queued + " queued. Refusing is better than accepting work whose caller will have given up."); } /** Moves a queued call into execution. */ - public void promoteFromQueue() { - if (queued.get() > 0) { - queued.decrementAndGet(); - inFlight.incrementAndGet(); + public synchronized void promoteFromQueue() { + if (queued > 0) { + queued--; + inFlight++; } } /** Releases a finished call. */ - public void release() { - if (inFlight.get() > 0) { - inFlight.decrementAndGet(); + public synchronized void release() { + if (inFlight > 0) { + inFlight--; } } /** How many calls are executing. */ - public int inFlight() { - return inFlight.get(); + public synchronized int inFlight() { + return inFlight; } /** How many calls are waiting. */ - public int queued() { - return queued.get(); + public synchronized int queued() { + return queued; } /** How many calls have been refused. */ - public int rejected() { - return rejected.get(); + public synchronized int rejected() { + return rejected; } } diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcApplicationInvocation.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcApplicationInvocation.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcApplicationInvocation.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcApplicationInvocation.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcExecutorProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcExecutorProfile.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcExecutorProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcExecutorProfile.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcNettyParityContract.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcNettyParityContract.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcNettyParityContract.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcNettyParityContract.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariant.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariant.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariant.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariant.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelector.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelector.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelector.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelector.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcResponseMapper.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcResponseMapper.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcResponseMapper.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcResponseMapper.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorChain.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorChain.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorChain.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorChain.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrder.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrder.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrder.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrder.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorStage.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorStage.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorStage.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerInterceptorStage.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerProfile.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerProfile.java similarity index 85% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerProfile.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerProfile.java index 6c75ff8..c6c03ef 100644 --- a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerProfile.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerProfile.java @@ -1,5 +1,6 @@ package dev.caskeleton.grpc.server; +import dev.caskeleton.grpc.api.policy.GrpcTransportLimits; import java.time.Duration; /** @@ -65,10 +66,19 @@ public record GrpcServerProfile( /** The Stable default profile on shaded Netty. */ public static GrpcServerProfile stableNetty(GrpcExecutorProfile executor) { + return stable(GrpcServerTransport.NETTY_SHADED, executor); + } + + /** + * The Stable default profile on {@code transport}: the platform's default message and metadata + * bounds ({@link GrpcTransportLimits}) and keep-alive/connection-age settings. + */ + public static GrpcServerProfile stable( + GrpcServerTransport transport, GrpcExecutorProfile executor) { return new GrpcServerProfile( - GrpcServerTransport.NETTY_SHADED, - 1024L * 1024L, - 8192, + transport, + GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES, Duration.ofSeconds(30), Duration.ofSeconds(10), Duration.ofSeconds(30), diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerTransport.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerTransport.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServerTransport.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServerTransport.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapter.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapter.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapter.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapter.java diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapterDescriptor.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapterDescriptor.java similarity index 100% rename from grpc/grpc-server/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapterDescriptor.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcServiceAdapterDescriptor.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlDecision.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlDecision.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlDecision.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlDecision.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicy.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicy.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeDecision.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeDecision.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeDecision.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeDecision.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeToken.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeToken.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeToken.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeToken.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodec.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodec.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodec.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodec.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriter.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriter.java similarity index 82% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriter.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriter.java index 166638a..c949d2f 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriter.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriter.java @@ -4,8 +4,9 @@ import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Optional; +import java.util.function.BooleanSupplier; import java.util.function.Consumer; -import java.util.function.LongSupplier; +import java.util.function.ToLongFunction; /** * The single writer every server stream goes through. @@ -27,7 +28,7 @@ public final class GrpcSerializedStreamWriter { private final GrpcStreamSequence sequence; private final GrpcFlowControlPolicy flowControl; private final Consumer> transport; - private final LongSupplier payloadSizer; + private final ToLongFunction payloadSizer; private final Deque> queue = new ArrayDeque<>(); private GrpcStreamWriterState state = GrpcStreamWriterState.OPEN; @@ -37,15 +38,15 @@ public final class GrpcSerializedStreamWriter { /** * @param transport the single consumer that actually calls the observer. Invoked only from {@link - * #flush}, which is synchronized, so the observer sees one thread. - * @param payloadSizer the serialized size of the next payload, for the byte bound + * #flush} and {@link #terminate}, which are synchronized, so the observer sees one thread. + * @param payloadSizer the serialized size of a payload, for the byte bound */ public GrpcSerializedStreamWriter( GrpcStreamId streamId, GrpcStreamSequence sequence, GrpcFlowControlPolicy flowControl, Consumer> transport, - LongSupplier payloadSizer) { + ToLongFunction payloadSizer) { if (streamId == null || sequence == null || flowControl == null @@ -70,7 +71,7 @@ public final class GrpcSerializedStreamWriter { if (!state.acceptsMessages()) { return GrpcStreamWriteResult.REJECTED_CLOSED; } - long nextBytes = payloadSizer.getAsLong(); + long nextBytes = payloadSizer.applyAsLong(payload); GrpcFlowControlDecision decision = flowControl.decide(queue.size(), queuedBytes, nextBytes, transportReady); return switch (decision.action()) { @@ -97,7 +98,11 @@ public final class GrpcSerializedStreamWriter { } } } - case PAUSE, PROCEED -> { + case PAUSE -> { + enqueue(kind, payload, snapshotVersion, resumeToken, nextBytes); + yield GrpcStreamWriteResult.ACCEPTED_PAUSE; + } + case PROCEED -> { enqueue(kind, payload, snapshotVersion, resumeToken, nextBytes); yield GrpcStreamWriteResult.ACCEPTED; } @@ -119,20 +124,22 @@ public final class GrpcSerializedStreamWriter { } /** - * Hands every queued message to the transport, in order, from this one thread. + * Hands queued messages to the transport, in order, from this one thread, while it is ready. * + * @param transportReady asked before each message ({@code ServerCallStreamObserver::isReady}); + * flushing stops at the first false and the rest stay queued for the next onReady * @return the sequence numbers flushed */ - public synchronized List flush() { + public synchronized List flush(BooleanSupplier transportReady) { java.util.List flushed = new java.util.ArrayList<>(); - while (!queue.isEmpty()) { - GrpcStreamEnvelope envelope = queue.pollFirst().envelope(); - transport.accept(envelope); - lastFlushedSequence = envelope.sequence(); - flushed.add(envelope.sequence()); + while (!queue.isEmpty() && transportReady.getAsBoolean()) { + QueuedEnvelope queued = queue.pollFirst(); + transport.accept(queued.envelope()); + queuedBytes = Math.max(0L, queuedBytes - queued.serializedBytes()); + lastFlushedSequence = queued.envelope().sequence(); + flushed.add(lastFlushedSequence); } - queuedBytes = 0L; - if (state == GrpcStreamWriterState.DRAINING) { + if (queue.isEmpty() && state == GrpcStreamWriterState.DRAINING) { state = GrpcStreamWriterState.TERMINATED; } return List.copyOf(flushed); diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcSlowConsumerPolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcSlowConsumerPolicy.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcSlowConsumerPolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcSlowConsumerPolicy.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmission.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmission.java similarity index 96% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmission.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmission.java index 2c58baf..4bfb7e7 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmission.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmission.java @@ -39,14 +39,15 @@ public final class GrpcStreamAdmission { if (callerFingerprint == null || callerFingerprint.isBlank()) { throw new IllegalArgumentException("stream admission needs a caller fingerprint"); } + // Global bound first: a caller refused here must not leave an empty per-caller entry behind. + if (openStreams.get() >= maxConcurrentStreams) { + return false; + } AtomicInteger callerCount = perCaller.computeIfAbsent(callerFingerprint, key -> new AtomicInteger()); if (callerCount.get() >= maxStreamsPerCaller) { return false; } - if (openStreams.get() >= maxConcurrentStreams) { - return false; - } callerCount.incrementAndGet(); openStreams.incrementAndGet(); return true; diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelope.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelope.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelope.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelope.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamGapDetector.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamGapDetector.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamGapDetector.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamGapDetector.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamHeartbeat.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamHeartbeat.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamHeartbeat.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamHeartbeat.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamId.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamId.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamId.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamId.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifecycleCoordinator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifecycleCoordinator.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifecycleCoordinator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifecycleCoordinator.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicy.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicy.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicy.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicy.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamSequence.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamSequence.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamSequence.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamSequence.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamTerminationReason.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamTerminationReason.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamTerminationReason.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamTerminationReason.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriteResult.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriteResult.java similarity index 73% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriteResult.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriteResult.java index 802acdb..0063222 100644 --- a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriteResult.java +++ b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriteResult.java @@ -11,6 +11,12 @@ package dev.caskeleton.grpc.streaming; public enum GrpcStreamWriteResult { /** Queued for the single writer. Not a delivery guarantee. */ ACCEPTED, + /** + * Queued, and the producer should stop until the transport is ready again (the queue reached its + * high-water mark or the transport is not ready). Writing on regardless fills the queue to its + * bound and ends the stream. + */ + ACCEPTED_PAUSE, /** The bounded queue is full and the profile drops rather than terminates. */ DROPPED, /** The queue overflowed and the stream is being terminated. */ @@ -20,6 +26,6 @@ public enum GrpcStreamWriteResult { /** Whether the message entered the queue. */ public boolean queued() { - return this == ACCEPTED; + return this == ACCEPTED || this == ACCEPTED_PAUSE; } } diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriterState.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriterState.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriterState.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamWriterState.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/validation/GrpcTransportValidator.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/validation/GrpcTransportValidator.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/validation/GrpcTransportValidator.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/validation/GrpcTransportValidator.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptor.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptor.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptor.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptor.java diff --git a/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationViolation.java b/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationViolation.java similarity index 100% rename from grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationViolation.java rename to grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/validation/GrpcValidationViolation.java diff --git a/grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinatorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinatorTest.java similarity index 98% rename from grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinatorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinatorTest.java index de93009..4f64728 100644 --- a/grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinatorTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcDrainCoordinatorTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.api.Test; class GrpcDrainCoordinatorTest { private static final Instant START = Instant.parse("2026-08-30T10:00:00Z"); - private static final String DOCUMENTS = "hyeonworks.document.v1.DocumentService"; + private static final String DOCUMENTS = "caskeleton.document.v1.DocumentService"; private final AtomicInteger unaryCalls = new AtomicInteger(); private final AtomicInteger streams = new AtomicInteger(); diff --git a/grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotServiceTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotServiceTest.java similarity index 98% rename from grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotServiceTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotServiceTest.java index c512d49..cdc95fc 100644 --- a/grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotServiceTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcPlatformSnapshotServiceTest.java @@ -15,7 +15,7 @@ import org.junit.jupiter.api.Test; class GrpcPlatformSnapshotServiceTest { private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); - private static final String DOCUMENTS = "hyeonworks.document.v1.DocumentService"; + private static final String DOCUMENTS = "caskeleton.document.v1.DocumentService"; private final GrpcServiceHealthRegistry health = new GrpcServiceHealthRegistry(GrpcHealthPolicy.standalone()); diff --git a/grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicyTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicyTest.java similarity index 100% rename from grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicyTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcReflectionPolicyTest.java diff --git a/grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistryTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistryTest.java similarity index 64% rename from grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistryTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistryTest.java index d85f7c3..c3da8c3 100644 --- a/grpc/grpc-admin/src/test/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistryTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/admin/GrpcServiceHealthRegistryTest.java @@ -4,12 +4,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class GrpcServiceHealthRegistryTest { - private static final String DOCUMENTS = "hyeonworks.document.v1.DocumentService"; + private static final String DOCUMENTS = "caskeleton.document.v1.DocumentService"; @Test @DisplayName("an instance is not ready before its first check completes") @@ -37,7 +42,7 @@ class GrpcServiceHealthRegistryTest { GrpcServiceHealthRegistry registry = new GrpcServiceHealthRegistry(GrpcHealthPolicy.standalone()); - assertThat(registry.stateOf("hyeonworks.other.v1.OtherService")) + assertThat(registry.stateOf("caskeleton.other.v1.OtherService")) .isEqualTo(GrpcHealthState.SERVICE_UNKNOWN); } @@ -88,4 +93,47 @@ class GrpcServiceHealthRegistryTest { registry.markServing(DOCUMENTS); assertThat(registry.stateOf(DOCUMENTS)).isEqualTo(GrpcHealthState.DRAINING); } + + @Test + void aServiceMarkedServingWhileDrainBeginsNeverReturnsTheInstanceToServing() throws Exception { + // when + Set outcomes = outcomesOfServingRacingDrain(); + + // then + assertThat(outcomes).containsExactly("DRAINING/DRAINING"); + } + + /** Races markServing against beginDraining, round after round, recording service/global. */ + private static Set outcomesOfServingRacingDrain() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Set outcomes = new TreeSet<>(); + for (int round = 0; round < 1000; round++) { + GrpcServiceHealthRegistry registry = + new GrpcServiceHealthRegistry(GrpcHealthPolicy.standalone()); + registry.register(DOCUMENTS); + CyclicBarrier start = new CyclicBarrier(2); + Future serving = + pool.submit( + () -> { + start.await(); + registry.markServing(DOCUMENTS); + return null; + }); + Future drain = + pool.submit( + () -> { + start.await(); + registry.beginDraining(); + return null; + }); + serving.get(); + drain.get(); + outcomes.add(registry.stateOf(DOCUMENTS) + "/" + registry.globalState()); + } + return outcomes; + } finally { + pool.shutdownNow(); + } + } } diff --git a/grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistryTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistryTest.java similarity index 70% rename from grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistryTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistryTest.java index 796e4a1..b1ceb3e 100644 --- a/grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistryTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcChannelRuntimeRegistryTest.java @@ -6,6 +6,12 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.grpc.core.GrpcChannelProfileName; import java.time.Duration; import java.time.Instant; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -125,4 +131,52 @@ class GrpcChannelRuntimeRegistryTest { .extracting(Class::getName) .noneMatch(name -> name.startsWith("io.grpc.")); } + + @Test + void racingRotationsDrainEveryReplacedRuntimeAndKeepTheNewestCurrent() throws Exception { + // when + Set outcomes = outcomesOfRacingRotations(); + + // then + assertThat(outcomes).isSubsetOf("3 draining [1]", "3 draining [1, 2]"); + } + + /** Races rotate(2) against rotate(3) on a profile at generation 1, round after round. */ + private static Set outcomesOfRacingRotations() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Set outcomes = new TreeSet<>(); + for (int round = 0; round < 1000; round++) { + GrpcChannelRuntimeRegistry registry = + new GrpcChannelRuntimeRegistry(GrpcChannelDrainPolicy.stable()); + registry.install(generation(1)); + CyclicBarrier start = new CyclicBarrier(2); + Future a = pool.submit(() -> rotateIgnoringRefusal(registry, start, 2)); + Future b = pool.submit(() -> rotateIgnoringRefusal(registry, start, 3)); + a.get(); + b.get(); + outcomes.add( + registry.require(PROFILE).generation().generation() + + " draining " + + registry.draining(PROFILE).stream() + .map(runtime -> runtime.generation().generation()) + .sorted() + .toList()); + } + return outcomes; + } finally { + pool.shutdownNow(); + } + } + + private static Void rotateIgnoringRefusal( + GrpcChannelRuntimeRegistry registry, CyclicBarrier start, long next) throws Exception { + start.await(); + try { + registry.rotate(generation(next), NOW); + } catch (IllegalArgumentException refused) { + // the other rotator installed a newer generation first + } + return null; + } } diff --git a/grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicyTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicyTest.java similarity index 99% rename from grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicyTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicyTest.java index 1d663b9..04e973d 100644 --- a/grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicyTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcClientMetadataPolicyTest.java @@ -23,7 +23,7 @@ class GrpcClientMetadataPolicyTest { private static final GrpcMetadataKey CORRELATION = GrpcMetadataKey.ascii("x-correlation-id"); private static final GrpcMetadataKey TENANT = GrpcMetadataKey.ascii("x-tenant-context"); private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); private static GrpcClientMetadataPolicy policy(boolean crossesBoundary) { diff --git a/grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfileTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfileTest.java similarity index 100% rename from grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfileTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcNamedChannelProfileTest.java diff --git a/grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcTypedStubFactoryTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcTypedStubFactoryTest.java similarity index 93% rename from grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcTypedStubFactoryTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcTypedStubFactoryTest.java index 8203a61..021d4e8 100644 --- a/grpc/grpc-client/src/test/java/dev/caskeleton/grpc/client/GrpcTypedStubFactoryTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/client/GrpcTypedStubFactoryTest.java @@ -19,7 +19,7 @@ class GrpcTypedStubFactoryTest { private static final GrpcChannelProfileName PROFILE = new GrpcChannelProfileName("documents-read"); private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); /** Stands in for a generated blocking stub. */ @@ -122,8 +122,10 @@ class GrpcTypedStubFactoryTest { GrpcStubPolicyApplier.CallPolicy generous = applier.applyTo(GET, Duration.ofSeconds(30)); GrpcStubPolicyApplier.CallPolicy tight = applier.applyTo(GET, Duration.ofMillis(300)); - assertThat(generous.deadline().remaining()).isEqualTo(Duration.ofMillis(1800)); - assertThat(tight.deadline().remaining()).isEqualTo(Duration.ofMillis(100)); + // The budget is live: a few milliseconds have passed since applyTo computed it. + assertThat(generous.deadline().remaining()) + .isBetween(Duration.ofMillis(1700), Duration.ofMillis(1800)); + assertThat(tight.deadline().remaining()).isBetween(Duration.ZERO, Duration.ofMillis(100)); assertThat(tight.waitForReady().queue()).isFalse(); } } diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/context/GrpcContextBinderTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/context/GrpcContextBinderTest.java similarity index 86% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/context/GrpcContextBinderTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/context/GrpcContextBinderTest.java index a97f73c..1e1d115 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/context/GrpcContextBinderTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/context/GrpcContextBinderTest.java @@ -11,6 +11,7 @@ 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 io.grpc.Context; import java.time.Duration; import java.time.Instant; import java.util.Map; @@ -19,6 +20,7 @@ import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -26,7 +28,7 @@ import org.junit.jupiter.api.Test; class GrpcContextBinderTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static GrpcContextSnapshot snapshot(Instant credentialExpiry) { GrpcRequestContext request = @@ -156,4 +158,29 @@ class GrpcContextBinderTest { assertThat(actor).isEqualTo("actor-1"); assertThat(binder.current()).isEmpty(); } + + @Test + void wrappedWorkSeesTheSubmittingCallsCancellationOnAnotherThread() throws Exception { + // given + GrpcContextBinder binder = new GrpcContextBinder(GrpcContextPropagationPolicy.stable()); + Context.CancellableContext call = Context.current().withCancellation(); + AtomicBoolean cancelledInside = new AtomicBoolean(); + AtomicReference wrapped = new AtomicReference<>(); + call.run( + () -> + binder.runWith( + snapshot(null), + () -> + wrapped.set( + binder.wrap(() -> cancelledInside.set(Context.current().isCancelled()))))); + call.cancel(new IllegalStateException("the client went away")); + Thread worker = new Thread(wrapped.get()); + + // when + worker.start(); + worker.join(); + + // then + assertThat(cancelledInside).isTrue(); + } } diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinatorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinatorTest.java similarity index 100% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinatorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/deadline/GrpcCancellationCoordinatorTest.java diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculatorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculatorTest.java similarity index 97% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculatorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculatorTest.java index b158c98..71826cc 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculatorTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/deadline/GrpcDeadlineCalculatorTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; class GrpcDeadlineCalculatorTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcDeadlineProfile TWO_SECONDS = GrpcDeadlineProfile.of(Duration.ofSeconds(2)); private static final GrpcMethodPolicy READ = GrpcMethodPolicy.readOnlyUnary(GET, TWO_SECONDS); @@ -86,7 +86,7 @@ class GrpcDeadlineCalculatorTest { GrpcMethodPolicyCatalog.builder() .register( GrpcMethodPolicy.readOnlyUnary( - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/ListDocuments"), + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/ListDocuments"), TWO_SECONDS)) .build(); Map> dependencies = diff --git a/grpc/grpc-discovery/src/test/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidatorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidatorTest.java similarity index 100% rename from grpc/grpc-discovery/src/test/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidatorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/discovery/GrpcDiscoveryPolicyValidatorTest.java diff --git a/grpc/grpc-discovery/src/test/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileTest.java similarity index 100% rename from grpc/grpc-discovery/src/test/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/discovery/GrpcKubernetesProfileTest.java diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/error/GrpcErrorMapperTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/error/GrpcErrorMapperTest.java similarity index 99% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/error/GrpcErrorMapperTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/error/GrpcErrorMapperTest.java index 9fc3603..86e01af 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/error/GrpcErrorMapperTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/error/GrpcErrorMapperTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test; class GrpcErrorMapperTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private final GrpcErrorMapper mapper = new GrpcErrorMapper("document.v1", () -> "exec-0001"); diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java similarity index 97% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java index afb8e98..972630e 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.idempotency; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; import dev.caskeleton.grpc.core.GrpcMethodName; import java.time.Instant; import java.util.Optional; @@ -11,7 +12,7 @@ import org.junit.jupiter.api.Test; class GrpcCompletionReconcilerTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); private static final String CALLER = "tenant-1|actor-1"; private static final String KEY = "order-2026-0001"; diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java similarity index 73% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java index 51b8dea..6ed3d16 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java @@ -4,6 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; +import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; +import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; import dev.caskeleton.grpc.api.policy.GrpcMethodPolicy; import dev.caskeleton.grpc.api.policy.GrpcMethodPolicyCatalog; import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile; @@ -12,15 +16,21 @@ import dev.caskeleton.grpc.core.GrpcMethodName; import dev.caskeleton.grpc.core.RpcType; import java.time.Duration; import java.time.Instant; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class GrpcIdempotencyInterceptorTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcDeadlineProfile TEN_SECONDS = GrpcDeadlineProfile.of(Duration.ofSeconds(10)); private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); @@ -133,6 +143,57 @@ class GrpcIdempotencyInterceptorTest { .isEqualTo(GrpcIdempotencyDecision.Outcome.PROCEED); } + @Test + void aRetryOfATerminallyFailedOperationReclaimsItBeforeProceeding() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + interceptor.recordFailure(CREATE, CALLER, KEY, NOW.plusSeconds(1)); + + // when + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plusSeconds(2)); + + // then + assertThat( + ledger + .find( + new GrpcOperationIdentity( + CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY))) + .map(GrpcOperationLedgerRecord::state)) + .contains(GrpcOperationLedgerState.IN_PROGRESS); + } + + @Test + void concurrentRetriesOfATerminallyFailedOperationProceedOnlyOnce() throws Exception { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + interceptor.recordFailure(CREATE, CALLER, KEY, NOW.plusSeconds(1)); + CountDownLatch start = new CountDownLatch(1); + Callable retry = + () -> { + start.await(); + return interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plusSeconds(2)).outcome(); + }; + + // when + List outcomes; + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(retry); + Future second = executor.submit(retry); + start.countDown(); + outcomes = List.of(first.get(), second.get()); + } + + // then + assertThat(outcomes) + .containsExactlyInAnyOrder( + GrpcIdempotencyDecision.Outcome.PROCEED, + GrpcIdempotencyDecision.Outcome.REJECT_IN_PROGRESS); + } + @Test @DisplayName("one caller's key does not suppress another caller's write") void oneCallersKeyDoesNotSuppressAnother() { diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplayBoundTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplayBoundTest.java similarity index 100% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplayBoundTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOutcomeReplayBoundTest.java diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicyTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicyTest.java similarity index 100% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicyTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/policy/GrpcPayloadBoundaryPolicyTest.java diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibilityTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibilityTest.java similarity index 98% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibilityTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibilityTest.java index b3c1b95..16c2078 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibilityTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryEligibilityTest.java @@ -22,11 +22,11 @@ import org.junit.jupiter.api.Test; class GrpcRetryEligibilityTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName WATCH = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/WatchDocuments"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); private static final GrpcDeadlineProfile TEN_SECONDS = GrpcDeadlineProfile.of(Duration.ofSeconds(10)); private static final GrpcMethodPolicy READ = GrpcMethodPolicy.readOnlyUnary(GET, TEN_SECONDS); diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidatorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidatorTest.java similarity index 96% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidatorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidatorTest.java index 4eb597d..b6905bd 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidatorTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcRetryOwnershipValidatorTest.java @@ -20,11 +20,11 @@ import org.junit.jupiter.api.Test; class GrpcRetryOwnershipValidatorTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName WATCH = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/WatchDocuments"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/WatchDocuments"); private static final GrpcDeadlineProfile TWO_SECONDS = GrpcDeadlineProfile.of(Duration.ofSeconds(2)); @@ -83,7 +83,7 @@ class GrpcRetryOwnershipValidatorTest { @DisplayName("a service config entry naming a method the catalog does not declare is reported") void aRenamedMethodLeavesItsEntryMatchingNothing() { GrpcMethodName renamed = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocumentV2"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocumentV2"); GrpcServiceConfigPolicy config = new GrpcServiceConfigPolicy( GrpcRetryOwner.GRPC_PLATFORM, diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidatorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidatorTest.java similarity index 98% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidatorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidatorTest.java index a5bec3b..5608c70 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidatorTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/resilience/GrpcWaitForReadyValidatorTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; class GrpcWaitForReadyValidatorTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcDeadlineProfile TEN_SECONDS = GrpcDeadlineProfile.of(Duration.ofSeconds(10)); @@ -91,7 +91,7 @@ class GrpcWaitForReadyValidatorTest { GrpcWaitForReadyValidator.decide( policyWith(WaitForReadyPolicy.WORKER_OPT_IN), GrpcWaitForReadyProfile.worker(Duration.ofSeconds(30)), - new GrpcDeadlineBudget(Duration.ofSeconds(5), TEN_SECONDS)); + new GrpcDeadlineBudget(Duration.ofSeconds(5), TEN_SECONDS, () -> 0L)); GrpcWaitForReadyDecision tightBudget = GrpcWaitForReadyValidator.decide( policyWith(WaitForReadyPolicy.WORKER_OPT_IN), diff --git a/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManagerTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManagerTest.java new file mode 100644 index 0000000..9da1db1 --- /dev/null +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManagerTest.java @@ -0,0 +1,108 @@ +package dev.caskeleton.grpc.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.Consumer; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class GrpcCredentialRotationManagerTest { + + private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); + private static final int ROUNDS = 20_000; + + @Test + void racingRotationsNeverLeaveAnOlderGenerationCurrent() throws Exception { + // when + long lowest = + lowestCurrentAfterRacing( + manager -> rotateIgnoringRefusal(manager, 3L), manager -> manager.rotate(gen(4L), NOW)); + + // then + assertThat(lowest).isEqualTo(4L); + } + + @Test + void aDrainCompletedDuringARotationNeverRevertsTheNewGeneration() throws Exception { + // when + long lowest = + lowestCurrentAfterRacing( + manager -> manager.rotate(gen(3L), NOW), manager -> manager.completeDrain(gen(1L))); + + // then + assertThat(lowest).isEqualTo(3L); + } + + @Test + @DisplayName("이전 세대의 drain 완료 보고는 그 사이 새 rotation이 시작한 drain을 끝내지 않는다") + void completingAnOlderDrainLeavesTheNewerDrainInPlace() { + // given + GrpcCredentialRotationManager manager = + new GrpcCredentialRotationManager(gen(1L), Duration.ofSeconds(30)); + manager.rotate(gen(2L), NOW); + manager.rotate(gen(3L), NOW); + + // when + manager.completeDrain(gen(1L)); + + // then + assertThat(manager.draining()).contains(gen(2L)); + } + + /** + * Starts each round at generation 2 (draining 1), runs {@code first} and {@code second} at the + * same moment, and returns the lowest generation left current over all rounds. + */ + private static long lowestCurrentAfterRacing( + Consumer first, Consumer second) + throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + long lowest = Long.MAX_VALUE; + for (int round = 0; round < ROUNDS; round++) { + GrpcCredentialRotationManager manager = + new GrpcCredentialRotationManager(gen(1L), Duration.ofSeconds(30)); + manager.rotate(gen(2L), NOW); + CyclicBarrier start = new CyclicBarrier(2); + Future a = pool.submit(() -> run(start, first, manager)); + Future b = pool.submit(() -> run(start, second, manager)); + a.get(); + b.get(); + lowest = Math.min(lowest, manager.current().generation()); + } + return lowest; + } finally { + pool.shutdownNow(); + } + } + + private static Void run( + CyclicBarrier start, + Consumer action, + GrpcCredentialRotationManager manager) + throws Exception { + start.await(); + action.accept(manager); + return null; + } + + /** The losing rotator of a race is refused, which is the correct outcome, not a failure. */ + private static void rotateIgnoringRefusal(GrpcCredentialRotationManager manager, long next) { + try { + manager.rotate(gen(next), NOW); + } catch (IllegalArgumentException refused) { + // superseded by the other rotator + } + } + + private static GrpcCredentialGeneration gen(long generation) { + return new GrpcCredentialGeneration( + generation, "vault://v" + generation, NOW, NOW.plusSeconds(3600)); + } +} diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/security/GrpcTlsProfileTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/security/GrpcTlsProfileTest.java similarity index 99% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/security/GrpcTlsProfileTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/security/GrpcTlsProfileTest.java index dba6213..4804462 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/security/GrpcTlsProfileTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/security/GrpcTlsProfileTest.java @@ -140,7 +140,7 @@ class GrpcTlsProfileTest { assertThat(manager.drainExpired(now.plusSeconds(29))).isFalse(); assertThat(manager.drainExpired(now.plusSeconds(30))).isTrue(); - manager.completeDrain(); + manager.completeDrain(first); assertThat(manager.draining()).isEmpty(); } diff --git a/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcAdmissionControllerTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcAdmissionControllerTest.java new file mode 100644 index 0000000..895fdf5 --- /dev/null +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcAdmissionControllerTest.java @@ -0,0 +1,55 @@ +package dev.caskeleton.grpc.server; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.Test; + +class GrpcAdmissionControllerTest { + + private static final int CALLERS = 8; + private static final int ROUNDS = 500; + + @Test + void racingCallersNeverGetPastTheConcurrencyAndQueueBounds() throws Exception { + // when + int mostAdmitted = mostAdmittedOverRounds(); + + // then + assertThat(mostAdmitted).isEqualTo(2); + } + + /** Races {@link #CALLERS} callers at a 1-running, 1-queued controller, round after round. */ + private static int mostAdmittedOverRounds() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(CALLERS); + try { + int most = 0; + for (int round = 0; round < ROUNDS; round++) { + GrpcAdmissionController controller = new GrpcAdmissionController(1, 1); + CyclicBarrier start = new CyclicBarrier(CALLERS); + List> admitted = new ArrayList<>(); + for (int caller = 0; caller < CALLERS; caller++) { + admitted.add( + pool.submit( + () -> { + start.await(); + return controller.tryAdmit().admitted(); + })); + } + int count = 0; + for (Future result : admitted) { + count += result.get() ? 1 : 0; + } + most = Math.max(most, count); + } + return most; + } finally { + pool.shutdownNow(); + } + } +} diff --git a/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelectorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelectorTest.java similarity index 100% rename from grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelectorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcNettyVariantSelectorTest.java diff --git a/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrderTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrderTest.java similarity index 100% rename from grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrderTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcServerInterceptorOrderTest.java diff --git a/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcServerProfileTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcServerProfileTest.java similarity index 100% rename from grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcServerProfileTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcServerProfileTest.java diff --git a/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcServiceAdapterTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcServiceAdapterTest.java similarity index 99% rename from grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcServiceAdapterTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcServiceAdapterTest.java index 997b4a2..b202250 100644 --- a/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/server/GrpcServiceAdapterTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcServiceAdapterTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test; class GrpcServiceAdapterTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private record CreateRequest(String title) {} diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicyTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicyTest.java similarity index 100% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicyTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcFlowControlPolicyTest.java diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodecTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodecTest.java similarity index 100% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodecTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcResumeTokenCodecTest.java diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriterTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriterTest.java similarity index 79% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriterTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriterTest.java index 7976eea..767142e 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriterTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcSerializedStreamWriterTest.java @@ -9,6 +9,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -23,7 +24,7 @@ class GrpcSerializedStreamWriterTest { private GrpcSerializedStreamWriter writer( GrpcFlowControlPolicy policy, long messageSize) { return new GrpcSerializedStreamWriter<>( - STREAM, GrpcStreamSequence.forNewStream(STREAM), policy, sent::add, () -> messageSize); + STREAM, GrpcStreamSequence.forNewStream(STREAM), policy, sent::add, payload -> messageSize); } @Test @@ -38,7 +39,7 @@ class GrpcSerializedStreamWriterTest { assertThat(result.queued()).isTrue(); assertThat(sent).isEmpty(); - assertThat(writer.flush()).containsExactly(1L); + assertThat(writer.flush(() -> true)).containsExactly(1L); assertThat(sent).hasSize(1); } @@ -76,7 +77,7 @@ class GrpcSerializedStreamWriterTest { } assertThat(sent).isEmpty(); - List flushed = writer.flush(); + List flushed = writer.flush(() -> true); assertThat(flushed).hasSize(producers * perProducer); assertThat(flushed).isSorted(); assertThat(flushed).doesNotHaveDuplicates(); @@ -121,7 +122,7 @@ class GrpcSerializedStreamWriterTest { GrpcStreamSequence.forNewStream(STREAM), new GrpcFlowControlPolicy(10, 1000L, 9, GrpcSlowConsumerPolicy.DROP_OLDEST), sent::add, - nextSize::get); + payload -> nextSize.get()); nextSize.set(900L); assertThat(writer.write(GrpcStreamEnvelope.Kind.LIVE, "large", null, null, true)) @@ -149,7 +150,7 @@ class GrpcSerializedStreamWriterTest { GrpcStreamSequence.forNewStream(STREAM), new GrpcFlowControlPolicy(10, 700L, 9, GrpcSlowConsumerPolicy.DROP_OLDEST), sent::add, - nextSize::get); + payload -> nextSize.get()); writer.write(GrpcStreamEnvelope.Kind.LIVE, "first", null, null, true); writer.write(GrpcStreamEnvelope.Kind.LIVE, "second", null, null, true); @@ -179,7 +180,7 @@ class GrpcSerializedStreamWriterTest { void cancellingKeepsTheLastFlushedPositionAsEvidence() { GrpcSerializedStreamWriter writer = writer(GrpcFlowControlPolicy.stable(), 8L); writer.write(GrpcStreamEnvelope.Kind.LIVE, "first", null, null, true); - writer.flush(); + writer.flush(() -> true); writer.write(GrpcStreamEnvelope.Kind.LIVE, "second", null, null, true); long lastFlushed = writer.discardQueued(); @@ -189,4 +190,54 @@ class GrpcSerializedStreamWriterTest { assertThat(writer.queuedMessages()).isZero(); assertThat(sent).hasSize(1); } + + @Test + void theByteBoundCountsEachPayloadsOwnSize() { + // given + GrpcSerializedStreamWriter writer = + new GrpcSerializedStreamWriter<>( + STREAM, + GrpcStreamSequence.forNewStream(STREAM), + new GrpcFlowControlPolicy(10, 10L, 9, GrpcSlowConsumerPolicy.TERMINATE), + sent::add, + payload -> payload.length()); + writer.write(GrpcStreamEnvelope.Kind.LIVE, "eight-by", null, null, true); + + // when + GrpcStreamWriteResult result = + writer.write(GrpcStreamEnvelope.Kind.LIVE, "four", null, null, true); + + // then + assertThat(result).isEqualTo(GrpcStreamWriteResult.OVERFLOW_TERMINATING); + } + + @Test + void aWriteWhileTheTransportIsNotReadyTellsTheProducerToPause() { + // given + GrpcSerializedStreamWriter writer = writer(GrpcFlowControlPolicy.stable(), 8L); + + // when + GrpcStreamWriteResult result = + writer.write(GrpcStreamEnvelope.Kind.LIVE, "row", null, null, false); + + // then + assertThat(result) + .extracting(r -> r, GrpcStreamWriteResult::queued) + .containsExactly(GrpcStreamWriteResult.ACCEPTED_PAUSE, true); + } + + @Test + void flushStopsWhenTheTransportStopsBeingReady() { + // given + GrpcSerializedStreamWriter writer = writer(GrpcFlowControlPolicy.stable(), 8L); + writer.write(GrpcStreamEnvelope.Kind.LIVE, "first", null, null, true); + writer.write(GrpcStreamEnvelope.Kind.LIVE, "second", null, null, true); + AtomicInteger readyChecks = new AtomicInteger(); + + // when + List flushed = writer.flush(() -> readyChecks.getAndIncrement() == 0); + + // then + assertThat(flushed).containsExactly(1L); + } } diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmissionConcurrencyTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmissionConcurrencyTest.java similarity index 81% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmissionConcurrencyTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmissionConcurrencyTest.java index 8849c52..f335220 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmissionConcurrencyTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamAdmissionConcurrencyTest.java @@ -45,4 +45,17 @@ class GrpcStreamAdmissionConcurrencyTest { assertThat(admission.trackedCallers()).isZero(); } } + + @Test + void aCallerRefusedByTheGlobalBoundLeavesNoTrackedEntry() { + // given + GrpcStreamAdmission admission = new GrpcStreamAdmission(1, 1); + admission.tryAdmit("first"); + + // when + admission.tryAdmit("refused"); + + // then + assertThat(admission.trackedCallers()).isOne(); + } } diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelopeTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelopeTest.java similarity index 88% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelopeTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelopeTest.java index 9788b7f..ccbaa45 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelopeTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamEnvelopeTest.java @@ -104,18 +104,6 @@ class GrpcStreamEnvelopeTest { .isInstanceOf(IllegalArgumentException.class); } - @Test - @DisplayName("a profile that buffers live events until the snapshot completes is the default") - void theDefaultProfileBuffersLiveEventsUntilTheSnapshotCompletes() { - GrpcStreamProfile profile = GrpcStreamProfile.snapshotThenLive(); - - assertThat(profile.snapshotFirst()).isTrue(); - assertThat(profile.liveEventsBeforeSnapshotComplete()).isFalse(); - assertThat(profile.resumable()).isTrue(); - assertThatThrownBy(() -> new GrpcStreamProfile(false, true, true, 10, 1024L)) - .isInstanceOf(IllegalArgumentException.class); - } - @Test @DisplayName("a termination reason says whether to reconnect and whether the position survives") void terminationReasonsSayWhatToDoNext() { diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicyTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicyTest.java similarity index 100% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicyTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/streaming/GrpcStreamLifetimePolicyTest.java diff --git a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptorTest.java b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptorTest.java similarity index 99% rename from grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptorTest.java rename to grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptorTest.java index 73468e8..b7d328d 100644 --- a/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptorTest.java +++ b/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/validation/GrpcValidationInterceptorTest.java @@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test; class GrpcValidationInterceptorTest { - private static final String FULL_METHOD = "hyeonworks.document.v1.DocumentService/CreateDocument"; + private static final String FULL_METHOD = "caskeleton.document.v1.DocumentService/CreateDocument"; /** A UTF-8 marshaller, so the descriptor needs no generated message type. */ private static final MethodDescriptor.Marshaller UTF8 = diff --git a/grpc/grpc-server/build.gradle b/grpc/grpc-server/build.gradle deleted file mode 100644 index 26c8142..0000000 --- a/grpc/grpc-server/build.gradle +++ /dev/null @@ -1,17 +0,0 @@ -plugins { - id 'ca.grpc-platform-module' -} - -// Server boundary: the ArchUnit-shaped application boundary rules, the typed service adapter SPI, -// the interceptor order contract, and the Netty server/executor/admission profiles. -// -// The Netty profiles are configuration models, not Netty wiring — no netty dependency here. Real -// Netty lives in `grpc-testkit`'s certification lane, which is where transport evidence is produced. - -dependencies { - api project(':grpc:grpc-core-api') - api project(':grpc:grpc-policy') - - api "io.grpc:grpc-api" - api "io.grpc:grpc-stub" -} diff --git a/grpc/grpc-server/gradle.lockfile b/grpc/grpc-server/gradle.lockfile deleted file mode 100644 index 9369e83..0000000 --- a/grpc/grpc-server/gradle.lockfile +++ /dev/null @@ -1,91 +0,0 @@ -# This is a Gradle generated file for dependency locking. -# Manual edits can break the build and are not advised. -# This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs -com.github.spotbugs:spotbugs:4.10.2=spotbugs -com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath -com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.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= diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRules.java b/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRules.java deleted file mode 100644 index 0d62e92..0000000 --- a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRules.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.grpc.architecture; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * What a gRPC service adapter may not reach. - * - *

The list is package prefixes rather than a prose rule, so it can be applied by an architecture - * test, by a source scan and by a review checklist without three people deciding what "must not use - * a repository" covers. - * - *

The rule these encode is one of this repository's hard stops: a transport adapter that calls a - * repository has moved the use case into the transport, and the next caller of that use case — a - * scheduled job, a message consumer — either duplicates it or reaches through the controller. - */ -public final class GrpcApplicationBoundaryRules { - - /** Package prefixes an adapter may not reference. */ - private static final Set FORBIDDEN_PREFIXES = - Set.of( - "jakarta.persistence", - "org.hibernate", - "org.springframework.data", - "org.springframework.jdbc", - "org.springframework.orm", - "org.springframework.web.client", - "org.springframework.web.reactive.function.client", - "java.net.http", - "org.apache.kafka", - "org.springframework.kafka", - "org.springframework.amqp", - "software.amazon.awssdk", - "dev.caskeleton.adapter.outbound"); - - /** Exact types an adapter may not reference, where the package alone is too broad. */ - private static final Set FORBIDDEN_TYPES = - Set.of("javax.sql.DataSource", "java.sql.Connection", "java.sql.DriverManager"); - - private GrpcApplicationBoundaryRules() {} - - /** The forbidden package prefixes, for an architecture test to consume. */ - public static Set forbiddenPackagePrefixes() { - return FORBIDDEN_PREFIXES; - } - - /** The forbidden exact types. */ - public static Set forbiddenTypes() { - return FORBIDDEN_TYPES; - } - - /** - * Every forbidden reference in {@code referencedTypes}. - * - * @param adapterName the adapter under test, for the message - * @return an empty list when the adapter stays inside the boundary - */ - public static List violations(String adapterName, Set referencedTypes) { - if (adapterName == null || adapterName.isBlank()) { - throw new IllegalArgumentException("a boundary check names the adapter it is about"); - } - if (referencedTypes == null) { - throw new IllegalArgumentException("the referenced type set must not be null"); - } - List violations = new ArrayList<>(); - referencedTypes.stream() - .sorted() - .forEach( - referenced -> { - if (FORBIDDEN_TYPES.contains(referenced)) { - violations.add( - adapterName + " references " + referenced + ", which belongs behind a port"); - return; - } - FORBIDDEN_PREFIXES.stream() - .filter(prefix -> referenced.startsWith(prefix + ".")) - .findFirst() - .ifPresent( - prefix -> - violations.add( - adapterName - + " references " - + referenced - + " from forbidden package '" - + prefix - + "'; a transport adapter reaches persistence, messaging and " - + "HTTP only through an application port")); - }); - return List.copyOf(violations); - } -} diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcRawApiImportRule.java b/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcRawApiImportRule.java deleted file mode 100644 index 5a9a20a..0000000 --- a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcRawApiImportRule.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.grpc.architecture; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Keeps raw gRPC construction APIs out of ordinary application code. - * - *

The types below are the ones that build a channel, a server or a call by hand. Every one of - * them bypasses a Stable guarantee: a hand-built {@code ManagedChannel} has no named profile, no - * deadline policy and no credential rotation; a hand-built {@code ClientCall} skips the interceptor - * chain entirely. They are legitimate inside the platform and inside generated code, which is why - * this rule takes an allowlist of packages rather than banning them outright. - */ -public final class GrpcRawApiImportRule { - - /** The construction APIs ordinary application code may not import. */ - private static final Set RAW_API_TYPES = - Set.of( - "io.grpc.ManagedChannelBuilder", - "io.grpc.ManagedChannel", - "io.grpc.ServerBuilder", - "io.grpc.Server", - "io.grpc.ClientCall", - "io.grpc.ClientCalls", - "io.grpc.MethodDescriptor", - "io.grpc.CallCredentials", - "io.grpc.netty.NettyChannelBuilder", - "io.grpc.netty.NettyServerBuilder", - "io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder", - "io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder", - "io.grpc.inprocess.InProcessChannelBuilder", - "io.grpc.inprocess.InProcessServerBuilder"); - - private static final Pattern IMPORT = - Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); - private static final Pattern PACKAGE = - Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); - - private final Set allowedPackagePrefixes; - - /** - * @param allowedPackagePrefixes packages where raw construction is the job — the platform's own - * leaves and the generated code root. Everything else reaches gRPC through a typed stub or a - * service adapter. - */ - public GrpcRawApiImportRule(Set allowedPackagePrefixes) { - if (allowedPackagePrefixes == null || allowedPackagePrefixes.isEmpty()) { - throw new IllegalArgumentException( - "a raw-API rule needs at least one allowed package; the platform itself has to build " - + "channels somewhere"); - } - this.allowedPackagePrefixes = Set.copyOf(allowedPackagePrefixes); - } - - /** This repository's rule: the platform leaves and the generated package may construct. */ - public static GrpcRawApiImportRule caSkeleton() { - return new GrpcRawApiImportRule(Set.of("dev.caskeleton.grpc", "hyeonworks.grpc")); - } - - /** The raw construction types this rule governs. */ - public static Set rawApiTypes() { - return RAW_API_TYPES; - } - - /** - * Every forbidden import in one Java source file. - * - * @return an empty list when the file is compliant, or when it is inside an allowed package - */ - public List violations(String fileName, String source) { - if (fileName == null || fileName.isBlank()) { - throw new IllegalArgumentException("a source file needs a name"); - } - if (source == null) { - throw new IllegalArgumentException("a source file needs its text"); - } - Matcher packageMatcher = PACKAGE.matcher(source); - String declaredPackage = packageMatcher.find() ? packageMatcher.group(1) : ""; - if (allowed(declaredPackage)) { - return List.of(); - } - - List violations = new ArrayList<>(); - Matcher imports = IMPORT.matcher(source); - while (imports.find()) { - String imported = imports.group(1); - if (RAW_API_TYPES.contains(imported)) { - violations.add( - fileName - + " imports " - + imported - + "; a hand-built channel, server or call has no named profile, no deadline policy " - + "and no interceptor chain. Use a typed stub or a service adapter."); - } - } - return List.copyOf(violations); - } - - /** Whether {@code packageName} may construct raw gRPC objects. */ - public boolean allowed(String packageName) { - return allowedPackagePrefixes.stream() - .anyMatch(prefix -> packageName.equals(prefix) || packageName.startsWith(prefix + ".")); - } -} diff --git a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcServiceAdapterMarker.java b/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcServiceAdapterMarker.java deleted file mode 100644 index 73c1139..0000000 --- a/grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcServiceAdapterMarker.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.grpc.architecture; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Marks a class as a gRPC service adapter, which is what the boundary rules are stated about. - * - *

An annotation rather than a naming convention, because a rule keyed on a suffix is a rule that - * stops applying the moment somebody names a class {@code DocumentGrpcFacade}. The marker is what a - * rule set can enumerate exactly. - * - *

Runtime retention so an architecture test can find the classes without a source scan. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface GrpcServiceAdapterMarker { - - /** The full method names this adapter serves, for cross-checking against the policy catalog. */ - String[] methods() default {}; -} diff --git a/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRulesTest.java b/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRulesTest.java deleted file mode 100644 index b3dcf09..0000000 --- a/grpc/grpc-server/src/test/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRulesTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package dev.caskeleton.grpc.architecture; - -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 GrpcApplicationBoundaryRulesTest { - - @Test - @DisplayName("an adapter reaching persistence, messaging or HTTP directly is refused") - void anAdapterMayNotReachInfrastructureDirectly() { - Set referenced = - Set.of( - "dev.caskeleton.application.document.CreateDocumentUseCase", - "jakarta.persistence.EntityManager", - "org.springframework.data.jpa.repository.JpaRepository", - "org.apache.kafka.clients.producer.KafkaProducer", - "java.net.http.HttpClient"); - - assertThat(GrpcApplicationBoundaryRules.violations("DocumentServiceAdapter", referenced)) - .hasSize(4) - .allSatisfy(violation -> assertThat(violation).startsWith("DocumentServiceAdapter")); - } - - @Test - @DisplayName("an adapter that only reaches application ports passes") - void anAdapterOnApplicationPortsPasses() { - assertThat( - GrpcApplicationBoundaryRules.violations( - "DocumentServiceAdapter", - Set.of( - "dev.caskeleton.application.document.CreateDocumentUseCase", - "dev.caskeleton.grpc.api.context.GrpcRequestContext"))) - .isEmpty(); - } - - @Test - @DisplayName("a raw DataSource or Connection is refused even though its package is not") - void exactTypesAreRefusedWherePackagesAreTooBroad() { - assertThat( - GrpcApplicationBoundaryRules.violations( - "DocumentServiceAdapter", Set.of("javax.sql.DataSource"))) - .singleElement() - .satisfies(violation -> assertThat(violation).contains("belongs behind a port")); - assertThat(GrpcApplicationBoundaryRules.forbiddenTypes()) - .contains("java.sql.Connection", "java.sql.DriverManager"); - } - - @Test - @DisplayName("an inbound adapter may not reach an outbound adapter") - void inboundMayNotReachOutbound() { - assertThat( - GrpcApplicationBoundaryRules.violations( - "DocumentServiceAdapter", - Set.of("dev.caskeleton.adapter.outbound.persistence.DocumentJpaRepository"))) - .hasSize(1); - } - - @Test - @DisplayName("ordinary application code may not import a raw channel, server or call builder") - void rawConstructionApisAreRefusedOutsideThePlatform() { - GrpcRawApiImportRule rule = GrpcRawApiImportRule.caSkeleton(); - String applicationSource = - """ - package dev.caskeleton.application.document; - - import io.grpc.ManagedChannelBuilder; - import java.util.List; - - class DocumentClient {} - """; - - assertThat(rule.violations("DocumentClient.java", applicationSource)) - .singleElement() - .satisfies( - violation -> - assertThat(violation) - .contains("io.grpc.ManagedChannelBuilder") - .contains("no interceptor chain")); - } - - @Test - @DisplayName("the platform's own packages and generated code may construct") - void thePlatformAndGeneratedCodeMayConstruct() { - GrpcRawApiImportRule rule = GrpcRawApiImportRule.caSkeleton(); - String platformSource = - """ - package dev.caskeleton.grpc.client; - - import io.grpc.ManagedChannelBuilder; - - class ChannelFactory {} - """; - String generatedSource = - """ - package hyeonworks.grpc.common.v1.generated; - - import io.grpc.MethodDescriptor; - - public final class DocumentServiceGrpc {} - """; - - assertThat(rule.violations("ChannelFactory.java", platformSource)).isEmpty(); - assertThat(rule.violations("DocumentServiceGrpc.java", generatedSource)).isEmpty(); - assertThat(rule.allowed("dev.caskeleton.grpc.server")).isTrue(); - assertThat(rule.allowed("dev.caskeleton.application")).isFalse(); - } - - @Test - @DisplayName("a rule with no allowed package is refused, since the platform must build somewhere") - void aRuleWithNoAllowedPackageIsRefused() { - assertThatThrownBy(() -> new GrpcRawApiImportRule(Set.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("build channels somewhere"); - } - - @Test - @DisplayName("the raw API list covers channel, server and call construction on every transport") - void theRawApiListCoversEveryConstructionPath() { - assertThat(GrpcRawApiImportRule.rawApiTypes()) - .contains( - "io.grpc.ManagedChannelBuilder", - "io.grpc.ServerBuilder", - "io.grpc.ClientCall", - "io.grpc.netty.NettyServerBuilder", - "io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder", - "io.grpc.inprocess.InProcessServerBuilder"); - } - - @Test - @DisplayName("the marker annotation is visible at runtime, so a rule can enumerate adapters") - void theMarkerIsVisibleAtRuntime() { - assertThat( - GrpcServiceAdapterMarker.class - .getAnnotation(java.lang.annotation.Retention.class) - .value()) - .isEqualTo(java.lang.annotation.RetentionPolicy.RUNTIME); - } -} diff --git a/grpc/grpc-spring-boot-starter/build.gradle b/grpc/grpc-spring-boot-starter/build.gradle index b85f08b..ad114e6 100644 --- a/grpc/grpc-spring-boot-starter/build.gradle +++ b/grpc/grpc-spring-boot-starter/build.gradle @@ -1,5 +1,7 @@ plugins { - id 'ca.platform-module' + // 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' id 'ca.spring-config' } @@ -11,16 +13,9 @@ plugins { // enforces it, and GrpcPlatformStartupValidatorTest asserts the same rule from the Java side. dependencies { api project(':grpc:grpc-core-api') - api project(':grpc:grpc-policy') - api project(':grpc:grpc-server') - api project(':grpc:grpc-client') - api project(':grpc:grpc-discovery') - api project(':grpc:grpc-admin') + api project(':grpc:grpc-runtime') api project(':grpc:grpc-observability') - implementation project(':grpc:grpc-proto-contract') - implementation project(':grpc:grpc-codegen') - implementation 'org.springframework.boot:spring-boot-autoconfigure' } diff --git a/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java b/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java index 2901f6c..8516939 100644 --- a/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java +++ b/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java @@ -10,11 +10,10 @@ import dev.caskeleton.grpc.client.GrpcNamedChannelProfile; import dev.caskeleton.grpc.context.GrpcContextBinder; import dev.caskeleton.grpc.context.GrpcContextPropagationPolicy; import dev.caskeleton.grpc.error.GrpcErrorMapper; +import dev.caskeleton.grpc.security.GrpcTlsProfile; import dev.caskeleton.grpc.server.GrpcAdmissionController; import dev.caskeleton.grpc.server.GrpcExecutorProfile; import dev.caskeleton.grpc.server.GrpcServerProfile; -import java.time.Duration; -import java.util.Set; import java.util.UUID; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartInitializingSingleton; @@ -34,7 +33,7 @@ import org.springframework.context.annotation.Bean; */ @AutoConfiguration @ConditionalOnProperty( - prefix = "ca-skeleton.grpc.platform", + prefix = "app.grpc.platform", name = "enabled", havingValue = "true", matchIfMissing = false) @@ -54,16 +53,7 @@ public class GrpcPlatformAutoConfiguration { @ConditionalOnMissingBean public GrpcServerProfile grpcServerProfile( GrpcPlatformProperties properties, GrpcExecutorProfile executorProfile) { - return new GrpcServerProfile( - properties.getTransport(), - 1024L * 1024L, - 8192, - Duration.ofSeconds(30), - Duration.ofSeconds(10), - Duration.ofSeconds(30), - Duration.ofMinutes(30), - Duration.ofSeconds(30), - executorProfile); + return GrpcServerProfile.stable(properties.getTransport(), executorProfile); } /** Admission control, sized from the executor. */ @@ -80,16 +70,23 @@ public class GrpcPlatformAutoConfiguration { return new GrpcServiceHealthRegistry(GrpcHealthPolicy.standalone()); } - /** The reflection policy, defaulted from the environment. */ + /** + * The reflection policy, defaulted from the environment. An unset environment gets the strictest + * floor here; the startup check then refuses the configuration with the reason. + */ @Bean @ConditionalOnMissingBean public GrpcReflectionPolicy grpcReflectionPolicy(GrpcPlatformProperties properties) { - return properties.getReflectionMode() == null - ? GrpcReflectionPolicy.defaultFor(properties.getEnvironment()) - : new GrpcReflectionPolicy( - properties.getReflectionMode(), - java.util.Set.of("admin"), - java.util.Set.of("ROLE_PLATFORM_ADMIN")); + if (properties.getReflectionMode() != null) { + return new GrpcReflectionPolicy( + properties.getReflectionMode(), + java.util.Set.of("admin"), + java.util.Set.of("ROLE_PLATFORM_ADMIN")); + } + return GrpcReflectionPolicy.defaultFor( + properties.getEnvironment() == null + ? GrpcTlsProfile.Environment.PROD + : properties.getEnvironment()); } /** The admin exposure gates. */ @@ -116,21 +113,22 @@ public class GrpcPlatformAutoConfiguration { /** * Runs the Stable startup validator against the bean graph after singleton assembly. * - *

The Gradle architecture gate owns dependency-graph isolation. Runtime validation therefore - * passes no synthetic dependency list; it validates only inputs a running process can actually - * observe: typed properties, the method-policy catalog and named client channels. + *

The Gradle architecture gate owns dependency-graph isolation. Runtime validation checks only + * inputs a running process can actually observe: typed properties, the method-policy catalog, + * named client channels and the server transport profile. */ @Bean public SmartInitializingSingleton grpcPlatformStartupCheck( GrpcPlatformProperties properties, ObjectProvider catalogs, - ObjectProvider channelProfiles) { + ObjectProvider channelProfiles, + GrpcServerProfile serverProfile) { return () -> GrpcPlatformStartupValidator.requireValid( properties, catalogs.getIfAvailable(() -> GrpcMethodPolicyCatalog.builder().build()), channelProfiles.orderedStream().toList(), - Set.of()); + serverProfile); } /** The shared error mapper. Its execution ids are random and carry no derived content. */ diff --git a/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java b/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java index 8f1e2dd..c480573 100644 --- a/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java +++ b/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java @@ -6,7 +6,7 @@ import dev.caskeleton.grpc.server.GrpcServerTransport; import org.springframework.boot.context.properties.ConfigurationProperties; /** - * The gRPC platform's typed configuration, bound from {@code ca-skeleton.grpc.platform.*}. + * The gRPC platform's typed configuration, bound from {@code app.grpc.platform.*}. * *

Off by default, like every other optional capability in this repository. A platform that * starts because its jar is on the classpath is a platform that opens a port on a deployment nobody @@ -16,14 +16,18 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * leaving a setting at its default — which is how a deployment ends up with production reflection * enabled because somebody wrote {@code reflection-mode} under the wrong prefix. */ -@ConfigurationProperties(prefix = "ca-skeleton.grpc.platform", ignoreUnknownFields = false) +@ConfigurationProperties(prefix = "app.grpc.platform", ignoreUnknownFields = false) public class GrpcPlatformProperties { /** Whether the platform is assembled at all. */ private boolean enabled; - /** Which environment this deployment is, which decides the TLS and reflection floors. */ - private GrpcTlsProfile.Environment environment = GrpcTlsProfile.Environment.LOCAL; + /** + * Which environment this deployment is, which decides the TLS and reflection floors. No default: + * a missing value used to mean LOCAL, which silently switched every TLS and reflection check off, + * so an enabled platform without it is refused at startup. + */ + private GrpcTlsProfile.Environment environment; /** The server transport. Only a production transport is accepted outside tests. */ private GrpcServerTransport transport = GrpcServerTransport.NETTY_SHADED; @@ -120,8 +124,16 @@ public class GrpcPlatformProperties { this.operationLedgerEnabled = operationLedgerEnabled; } - /** The reflection mode this deployment runs, defaulting to the environment's floor. */ + /** + * The reflection mode this deployment runs, defaulting to the environment's floor, and to + * disabled while the environment is unset (the startup check refuses that state). + */ public GrpcReflectionMode effectiveReflectionMode() { - return reflectionMode == null ? GrpcReflectionMode.defaultFor(environment) : reflectionMode; + if (reflectionMode != null) { + return reflectionMode; + } + return environment == null + ? GrpcReflectionMode.DISABLED + : GrpcReflectionMode.defaultFor(environment); } } diff --git a/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java b/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java index c72c09a..1f1a4de 100644 --- a/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java +++ b/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java @@ -6,10 +6,10 @@ import dev.caskeleton.grpc.api.policy.GrpcMethodPolicyCatalog; import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile; import dev.caskeleton.grpc.client.GrpcNamedChannelProfile; import dev.caskeleton.grpc.core.GrpcMethodName; -import dev.caskeleton.grpc.core.GrpcStableBuildInvariant; import dev.caskeleton.grpc.core.RpcType; import dev.caskeleton.grpc.discovery.GrpcDiscoveryPolicyValidator; import dev.caskeleton.grpc.resilience.GrpcRetryOwner; +import dev.caskeleton.grpc.server.GrpcServerProfile; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -33,29 +33,26 @@ public final class GrpcPlatformStartupValidator { /** * Every reason this configuration is refused. * - * @param stableModuleDependencies dependency ids supplied by a caller that can observe a runtime - * dependency set; the Spring auto-configuration passes an empty set because the Gradle - * registry gate is authoritative for the compiled graph + *

Stable-to-Advanced module isolation is not checked here: the Gradle registry gate ({@code + * verifyCleanArchitectureDependencies}) owns the compiled graph, and a running process has no + * dependency list to check it against. + * * @return an empty list when the configuration is safe to start */ public static List violations( GrpcPlatformProperties properties, GrpcMethodPolicyCatalog catalog, List channelProfiles, - Set stableModuleDependencies) { - if (properties == null - || catalog == null - || channelProfiles == null - || stableModuleDependencies == null) { + GrpcServerProfile serverProfile) { + if (properties == null || catalog == null || channelProfiles == null || serverProfile == null) { throw new IllegalArgumentException("startup validation needs every input"); } List violations = new ArrayList<>(); validateTransportAndSecurity(properties, violations); validateExecutor(properties, violations); - validateMethods(properties, catalog, violations); + validateMethods(properties, catalog, serverProfile, violations); validateChannels(channelProfiles, violations); - validateAdvancedIsolation(stableModuleDependencies, violations); return List.copyOf(violations); } @@ -68,9 +65,8 @@ public final class GrpcPlatformStartupValidator { GrpcPlatformProperties properties, GrpcMethodPolicyCatalog catalog, List channelProfiles, - Set stableModuleDependencies) { - List violations = - violations(properties, catalog, channelProfiles, stableModuleDependencies); + GrpcServerProfile serverProfile) { + List violations = violations(properties, catalog, channelProfiles, serverProfile); if (!violations.isEmpty()) { throw new GrpcPlatformConfigurationException(violations); } @@ -84,6 +80,12 @@ public final class GrpcPlatformStartupValidator { + properties.getTransport() + " may not serve production traffic; in-process evidence is not network evidence"); } + if (properties.getEnvironment() == null) { + violations.add( + "app.grpc.platform.environment is not set; the TLS and reflection floors depend on" + + " it, so it is refused rather than assumed LOCAL"); + return; + } boolean deployed = properties.getEnvironment().tlsRequired(); if (deployed && !properties.isTlsEnabled()) { violations.add("TLS is required in " + properties.getEnvironment() + " and is disabled"); @@ -114,9 +116,22 @@ public final class GrpcPlatformStartupValidator { } private static void validateMethods( - GrpcPlatformProperties properties, GrpcMethodPolicyCatalog catalog, List violations) { + GrpcPlatformProperties properties, + GrpcMethodPolicyCatalog catalog, + GrpcServerProfile serverProfile, + List violations) { for (GrpcMethodName method : sorted(catalog.methods())) { GrpcMethodPolicy policy = catalog.require(method); + if (policy.maxInboundMessageBytes() > serverProfile.maxInboundMessageBytes()) { + violations.add( + "method '" + + method.canonical() + + "' accepts " + + policy.maxInboundMessageBytes() + + "-byte messages but the server rejects anything over " + + serverProfile.maxInboundMessageBytes() + + "; the method's bound is a promise the transport breaks"); + } if (policy.rpcType() == RpcType.UNARY && policy.deadline().usable().isZero()) { violations.add( "Stable unary method '" @@ -172,16 +187,6 @@ public final class GrpcPlatformStartupValidator { } } - private static void validateAdvancedIsolation( - Set stableModuleDependencies, List violations) { - try { - GrpcStableBuildInvariant.requireNoAdvancedDependency( - "grpc-spring-boot-starter", stableModuleDependencies); - } catch (IllegalStateException leaked) { - violations.add(leaked.getMessage()); - } - } - private static List sorted(Set methods) { return methods.stream() .sorted(java.util.Comparator.comparing(GrpcMethodName::canonical)) diff --git a/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java b/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java index 714cebb..6957096 100644 --- a/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java +++ b/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.boot; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.util.Map; import org.junit.jupiter.api.Test; @@ -16,26 +17,45 @@ class GrpcPlatformAutoConfigurationContextTest { () -> start( Map.of( - "ca-skeleton.grpc.platform.enabled", "true", - "ca-skeleton.grpc.platform.environment", "PROD", - "ca-skeleton.grpc.platform.transport", "NETTY_SHADED", - "ca-skeleton.grpc.platform.tls-enabled", "true", - "ca-skeleton.grpc.platform.trust-all-certificates", "true"))) + "app.grpc.platform.enabled", "true", + "app.grpc.platform.environment", "PROD", + "app.grpc.platform.transport", "NETTY_SHADED", + "app.grpc.platform.tls-enabled", "true", + "app.grpc.platform.trust-all-certificates", "true"))) .isInstanceOf(GrpcPlatformConfigurationException.class) .hasMessageContaining("trust-all is enabled in PROD") .hasMessageContaining("providing none"); } + @Test + void enabledPlatformWithoutAnEnvironmentRefusesToStartInsteadOfAssumingLocal() { + // when + Throwable failure = + catchThrowable( + () -> + start( + Map.of( + "app.grpc.platform.enabled", "true", + "app.grpc.platform.transport", "NETTY_SHADED", + "app.grpc.platform.tls-enabled", "false", + "app.grpc.platform.reflection-mode", "ENABLED"))); + + // then + assertThat(failure) + .isInstanceOf(GrpcPlatformConfigurationException.class) + .hasMessageContaining("app.grpc.platform.environment is not set"); + } + @Test void coherentLocalConfigurationRunsTheStartupValidatorAndStarts() { try (AnnotationConfigApplicationContext context = start( Map.of( - "ca-skeleton.grpc.platform.enabled", "true", - "ca-skeleton.grpc.platform.environment", "LOCAL", - "ca-skeleton.grpc.platform.transport", "NETTY_SHADED", - "ca-skeleton.grpc.platform.executor-queue-capacity", "32", - "ca-skeleton.grpc.platform.executor-max-pool-size", "4"))) { + "app.grpc.platform.enabled", "true", + "app.grpc.platform.environment", "LOCAL", + "app.grpc.platform.transport", "NETTY_SHADED", + "app.grpc.platform.executor-queue-capacity", "32", + "app.grpc.platform.executor-max-pool-size", "4"))) { assertThat(context.getBean(GrpcPlatformProperties.class).isEnabled()).isTrue(); assertThat( context.getBeansOfType( @@ -49,9 +69,9 @@ class GrpcPlatformAutoConfigurationContextTest { try (AnnotationConfigApplicationContext context = start( Map.of( - "ca-skeleton.grpc.platform.enabled", "true", - "ca-skeleton.grpc.platform.environment", "LOCAL", - "ca-skeleton.grpc.platform.transport", "NETTY"))) { + "app.grpc.platform.enabled", "true", + "app.grpc.platform.environment", "LOCAL", + "app.grpc.platform.transport", "NETTY"))) { assertThat(context.getBean(dev.caskeleton.grpc.server.GrpcServerProfile.class).transport()) .isEqualTo(dev.caskeleton.grpc.server.GrpcServerTransport.NETTY); } diff --git a/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java b/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java index dac26da..dcffee9 100644 --- a/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java +++ b/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.grpc.admin.GrpcReflectionMode; import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; import dev.caskeleton.grpc.api.policy.GrpcMethodPolicy; import dev.caskeleton.grpc.api.policy.GrpcMethodPolicyCatalog; +import dev.caskeleton.grpc.api.policy.GrpcTransportLimits; import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile; import dev.caskeleton.grpc.api.policy.WaitForReadyPolicy; import dev.caskeleton.grpc.client.GrpcNamedChannelProfile; @@ -14,6 +15,8 @@ import dev.caskeleton.grpc.core.GrpcMethodName; import dev.caskeleton.grpc.core.RpcType; import dev.caskeleton.grpc.resilience.GrpcRetryOwner; import dev.caskeleton.grpc.security.GrpcTlsProfile; +import dev.caskeleton.grpc.server.GrpcExecutorProfile; +import dev.caskeleton.grpc.server.GrpcServerProfile; import dev.caskeleton.grpc.server.GrpcServerTransport; import java.io.IOException; import java.io.UncheckedIOException; @@ -23,22 +26,18 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.List; -import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class GrpcPlatformStartupValidatorTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcTlsProfile PROD_TLS = GrpcTlsProfile.serverAuthenticated(GrpcTlsProfile.Environment.PROD, "trust-bundle"); - private static final Set STABLE_DEPENDENCIES = - Set.of("grpc-core-api", "grpc-policy", "grpc-server", "grpc-client"); - private static GrpcPlatformProperties productionProperties() { GrpcPlatformProperties properties = new GrpcPlatformProperties(); properties.setEnabled(true); @@ -68,15 +67,50 @@ class GrpcPlatformStartupValidatorTest { GrpcRetryOwner.GRPC_PLATFORM)); } + private static GrpcServerProfile stableServer() { + return GrpcServerProfile.stableNetty(GrpcExecutorProfile.boundedPool(32, 256)); + } + + @Test + @DisplayName("method의 inbound 한도가 서버 profile의 한도보다 크면 기동을 거부한다") + void aMethodBoundAboveTheServerBoundIsRefused() { + // given + GrpcMethodPolicyCatalog catalog = + GrpcMethodPolicyCatalog.builder() + .register( + new GrpcMethodPolicy( + GET, + RpcType.UNARY, + RpcIdempotencyProfile.READ_ONLY, + GrpcDeadlineProfile.of(Duration.ofSeconds(2)), + WaitForReadyPolicy.DISABLED, + false, + 2 * GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, + 1024)) + .build(); + + // when + List violations = + GrpcPlatformStartupValidator.violations( + productionProperties(), catalog, oneChannel(), stableServer()); + + // then + assertThat(violations) + .containsExactly( + "method 'caskeleton.document.v1.DocumentService/GetDocument' accepts 2097152-byte" + + " messages but the server rejects anything over 1048576; the method's bound is a" + + " promise the transport breaks"); + } + @Test @DisplayName("a coherent production configuration starts") void aCoherentConfigurationStarts() { assertThat( GrpcPlatformStartupValidator.violations( - productionProperties(), healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + productionProperties(), healthyCatalog(), oneChannel(), stableServer())) .isEmpty(); GrpcPlatformStartupValidator.requireValid( - productionProperties(), healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES); + productionProperties(), healthyCatalog(), oneChannel(), stableServer()); } @Test @@ -93,7 +127,7 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - properties, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + properties, healthyCatalog(), oneChannel(), stableServer())) .anySatisfy(violation -> assertThat(violation).contains("not network evidence")); } @@ -107,11 +141,11 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - noTls, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + noTls, healthyCatalog(), oneChannel(), stableServer())) .anySatisfy(violation -> assertThat(violation).contains("TLS is required")); assertThat( GrpcPlatformStartupValidator.violations( - trustAll, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + trustAll, healthyCatalog(), oneChannel(), stableServer())) .anySatisfy(violation -> assertThat(violation).contains("providing none")); } @@ -123,7 +157,7 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - properties, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + properties, healthyCatalog(), oneChannel(), stableServer())) .anySatisfy(violation -> assertThat(violation).contains("published to anyone")); assertThat(productionProperties().effectiveReflectionMode()) .isEqualTo(GrpcReflectionMode.DISABLED); @@ -137,7 +171,7 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - properties, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + properties, healthyCatalog(), oneChannel(), stableServer())) .anySatisfy(violation -> assertThat(violation).contains("unbounded latency")); } @@ -162,7 +196,7 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - properties, catalog, oneChannel(), STABLE_DEPENDENCIES)) + properties, catalog, oneChannel(), stableServer())) .anySatisfy(violation -> assertThat(violation).contains("never honoured")); } @@ -185,7 +219,7 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - productionProperties(), catalog, oneChannel(), STABLE_DEPENDENCIES)) + productionProperties(), catalog, oneChannel(), stableServer())) .anySatisfy(violation -> assertThat(violation).contains("Advanced capability")); } @@ -207,21 +241,10 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - productionProperties(), healthyCatalog(), twoOwners, STABLE_DEPENDENCIES)) + productionProperties(), healthyCatalog(), twoOwners, stableServer())) .anySatisfy(violation -> assertThat(violation).contains("multiply the load")); } - @Test - @DisplayName("the Stable starter reaching an Advanced module is refused at startup too") - void advancedLeakIsRefusedAtStartup() { - Set leaked = Set.of("grpc-core-api", "grpc-policy", "grpc-advanced-streaming"); - - assertThat( - GrpcPlatformStartupValidator.violations( - productionProperties(), healthyCatalog(), oneChannel(), leaked)) - .anySatisfy(violation -> assertThat(violation).contains("grpc-advanced-streaming")); - } - @Test @DisplayName("a refusal names every violation at once") void aRefusalNamesEveryViolation() { @@ -233,7 +256,7 @@ class GrpcPlatformStartupValidatorTest { assertThatThrownBy( () -> GrpcPlatformStartupValidator.requireValid( - broken, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + broken, healthyCatalog(), oneChannel(), stableServer())) .isInstanceOf(GrpcPlatformConfigurationException.class) .satisfies( failure -> diff --git a/grpc/grpc-testkit/build.gradle b/grpc/grpc-testkit/build.gradle index fd9eb56..3387707 100644 --- a/grpc/grpc-testkit/build.gradle +++ b/grpc/grpc-testkit/build.gradle @@ -43,14 +43,8 @@ tasks.named('test') { dependencies { api project(':grpc:grpc-core-api') - api project(':grpc:grpc-policy') - api project(':grpc:grpc-server') - api project(':grpc:grpc-client') - api project(':grpc:grpc-discovery') - api project(':grpc:grpc-admin') + api project(':grpc:grpc-runtime') api project(':grpc:grpc-observability') - api project(':grpc:grpc-proto-contract') - api project(':grpc:grpc-codegen') api project(':grpc:grpc-operation-ledger-jpa') api "io.grpc:grpc-api" diff --git a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcCompatibilityMatrix.java b/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcCompatibilityMatrix.java deleted file mode 100644 index 4385302..0000000 --- a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcCompatibilityMatrix.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.grpc.release; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Which combinations a release is certified against, and which are only watched. - * - *

The distinction is what keeps a support claim honest. "Works with Spring Boot" is not a - * statement anyone can act on; "certified on the managed Boot platform, compatibility-checked - * against an upstream gRPC override, and not run at all on Edition 2024" is. - */ -public record GrpcCompatibilityMatrix(Map lanes) { - - /** How much a combination has actually been exercised. */ - public enum Lane { - /** Run on every release. A failure blocks. */ - CERTIFIED(true), - /** Run, but a failure is reported rather than blocking. */ - COMPATIBILITY(false), - /** Recorded and not run. */ - WATCH(false); - - private final boolean blocking; - - Lane(boolean blocking) { - this.blocking = blocking; - } - - /** Whether a failure in this lane blocks a release. */ - public boolean blocking() { - return blocking; - } - } - - /** Copies the lane map. */ - public GrpcCompatibilityMatrix { - if (lanes == null || lanes.isEmpty()) { - throw new IllegalArgumentException("a compatibility matrix names at least one lane"); - } - lanes = Map.copyOf(lanes); - if (lanes.values().stream().noneMatch(Lane::blocking)) { - throw new IllegalArgumentException( - "a matrix with no certified lane certifies nothing; every combination is optional"); - } - } - - /** This repository's matrix. */ - public static GrpcCompatibilityMatrix caSkeleton() { - return new GrpcCompatibilityMatrix( - Map.of( - "boot-managed-platform", Lane.CERTIFIED, - "proto3-explicit-optional", Lane.CERTIFIED, - "netty-shaded", Lane.CERTIFIED, - "netty-unshaded", Lane.COMPATIBILITY, - "upstream-grpc-java-override", Lane.COMPATIBILITY, - "protobuf-edition-2024", Lane.WATCH, - "protobuf-edition-2026", Lane.WATCH)); - } - - /** The lanes whose failure blocks a release. */ - public List blockingLanes() { - return lanes.entrySet().stream() - .filter(entry -> entry.getValue().blocking()) - .map(Map.Entry::getKey) - .sorted() - .toList(); - } - - /** - * Every blocking lane that has no result. - * - * @return an empty list when every certified lane ran - */ - public List missingResults(Map laneResults) { - if (laneResults == null) { - throw new IllegalArgumentException("a lane result map is required"); - } - List missing = new ArrayList<>(); - blockingLanes() - .forEach( - lane -> { - Boolean passed = laneResults.get(lane); - if (passed == null) { - missing.add("certified lane '" + lane + "' produced no result"); - } else if (!passed) { - missing.add("certified lane '" + lane + "' failed"); - } - }); - return List.copyOf(missing); - } -} diff --git a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcReleaseDecision.java b/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcReleaseDecision.java deleted file mode 100644 index 903ec41..0000000 --- a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcReleaseDecision.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.grpc.release; - -import java.util.List; - -/** - * Whether a Stable release may go out. - * - *

Blockers are a list rather than a boolean because a release conversation is about what is - * missing. "The gate failed" starts a search; "the fault lane did not run and the runbook is - * absent" starts the work. - */ -public record GrpcReleaseDecision(boolean approved, List blockers) { - - /** Requires blockers exactly when refused. */ - public GrpcReleaseDecision { - if (blockers == null) { - throw new IllegalArgumentException("a release decision lists its blockers, even when empty"); - } - blockers = List.copyOf(blockers); - if (approved && !blockers.isEmpty()) { - throw new IllegalArgumentException("an approved release has no blockers"); - } - if (!approved && blockers.isEmpty()) { - throw new IllegalArgumentException("a refused release says why"); - } - } - - /** - * An approved release. - * - *

Named {@code approve} rather than {@code approved}, which the record already uses for its - * accessor. - */ - public static GrpcReleaseDecision approve() { - return new GrpcReleaseDecision(true, List.of()); - } - - /** A refused release. */ - public static GrpcReleaseDecision refuse(List blockers) { - return new GrpcReleaseDecision(false, blockers); - } -} diff --git a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcReleaseEvidence.java b/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcReleaseEvidence.java deleted file mode 100644 index 7161c12..0000000 --- a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcReleaseEvidence.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.grpc.release; - -import dev.caskeleton.grpc.testkit.GrpcEvidenceGrade; -import java.util.EnumSet; -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * What a release actually has evidence for. - * - *

Graded, so a release cannot cite an in-process run as transport evidence. That substitution is - * the easiest one to make under time pressure and the hardest to spot afterwards: the suite name - * says "contract", the report says the platform is certified, and nothing in between records that - * no socket was opened. - */ -public record GrpcReleaseEvidence( - Set gradesRun, - Set certifiedCapabilities, - boolean runbookPresent, - boolean architectureDecisionRecordsPresent, - boolean supportMatrixPresent) { - - /** The grades a Stable release must have run. */ - private static final Set REQUIRED_GRADES = - EnumSet.of( - GrpcEvidenceGrade.CONTRACT, - GrpcEvidenceGrade.TRANSPORT, - GrpcEvidenceGrade.FAULT, - GrpcEvidenceGrade.PERFORMANCE); - - /** Copies both sets. */ - public GrpcReleaseEvidence { - if (gradesRun == null || certifiedCapabilities == null) { - throw new IllegalArgumentException("release evidence states what ran and what it certified"); - } - gradesRun = Set.copyOf(gradesRun); - certifiedCapabilities = Set.copyOf(certifiedCapabilities); - } - - /** The grades a Stable release requires. */ - public static Set requiredGrades() { - return Set.copyOf(REQUIRED_GRADES); - } - - /** The grades that were not run. */ - public Set missingGrades() { - Set missing = new LinkedHashSet<>(REQUIRED_GRADES); - missing.removeAll(gradesRun); - return Set.copyOf(missing); - } - - /** - * Whether {@code capability} is backed by a grade that can establish it. - * - *

The check the whole type exists for: a TLS claim needs a run that opened a socket. - */ - public boolean supports(String capability) { - if (!certifiedCapabilities.contains(capability)) { - return false; - } - return gradesRun.stream().anyMatch(grade -> grade.certifies().contains(capability)); - } -} diff --git a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcStableReleaseGate.java b/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcStableReleaseGate.java deleted file mode 100644 index 862f8d1..0000000 --- a/grpc/grpc-testkit/src/main/java/dev/caskeleton/grpc/release/GrpcStableReleaseGate.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.grpc.release; - -import dev.caskeleton.grpc.codegen.GrpcSchemaArtifactPublisher; -import dev.caskeleton.grpc.testkit.GrpcEvidenceGrade; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * The last check before a Stable release: every lane ran, every grade is present, and the - * operational documents exist. - * - *

Documents are a blocker rather than a follow-up. A platform whose failure modes are {@code - * COMPLETION_UNKNOWN} and a stream that needs a full resync is a platform whose on-call has to be - * told what to do about them; shipping the behaviour and writing the runbook afterwards means the - * first person to meet it is the one who has to work it out at three in the morning. - */ -public final class GrpcStableReleaseGate { - - private final GrpcCompatibilityMatrix matrix; - - /** Binds the gate to its compatibility matrix. */ - public GrpcStableReleaseGate(GrpcCompatibilityMatrix matrix) { - if (matrix == null) { - throw new IllegalArgumentException("a release gate needs a compatibility matrix"); - } - this.matrix = matrix; - } - - /** - * The release decision. - * - * @param schemaDecision the schema publisher's verdict, which carries the consumer-compile result - */ - public GrpcReleaseDecision evaluate( - GrpcReleaseEvidence evidence, - Map laneResults, - GrpcSchemaArtifactPublisher.PublishDecision schemaDecision) { - if (evidence == null || laneResults == null || schemaDecision == null) { - throw new IllegalArgumentException( - "a release decision needs evidence, lanes and the schema verdict"); - } - List blockers = new ArrayList<>(matrix.missingResults(laneResults)); - - evidence.missingGrades().stream() - .sorted() - .forEach( - grade -> - blockers.add( - grade - + " evidence was not produced; without it the release cannot claim " - + grade.certifies().stream().sorted().toList())); - - if (!schemaDecision.allowed()) { - schemaDecision.blockers().forEach(blocker -> blockers.add("schema: " + blocker)); - } - if (!evidence.runbookPresent()) { - blockers.add( - "the operations runbook is missing; COMPLETION_UNKNOWN and FULL_RESYNC_REQUIRED are " - + "states an on-call has to be told what to do about"); - } - if (!evidence.architectureDecisionRecordsPresent()) { - blockers.add("the architecture decision records are missing"); - } - if (!evidence.supportMatrixPresent()) { - blockers.add("the support matrix is missing, so no combination has a stated support level"); - } - return blockers.isEmpty() - ? GrpcReleaseDecision.approve() - : GrpcReleaseDecision.refuse(blockers); - } - - /** - * Whether a capability may be advertised as supported. - * - * @throws IllegalStateException when the evidence behind it is of the wrong grade - */ - public static void requireCertified(GrpcReleaseEvidence evidence, String capability) { - if (evidence == null) { - throw new IllegalArgumentException("release evidence is required"); - } - if (!evidence.supports(capability)) { - throw new IllegalStateException( - "capability '" - + capability - + "' is not certified by the evidence this release produced (" - + evidence.gradesRun().stream().map(GrpcEvidenceGrade::name).sorted().toList() - + ")"); - } - } - - /** The matrix in force. */ - public GrpcCompatibilityMatrix matrix() { - return matrix; - } -} diff --git a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/performance/GrpcPerformanceLaneTest.java b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/performance/GrpcPerformanceLaneTest.java index b1d1828..afe924b 100644 --- a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/performance/GrpcPerformanceLaneTest.java +++ b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/performance/GrpcPerformanceLaneTest.java @@ -33,7 +33,7 @@ import org.junit.jupiter.api.Test; class GrpcPerformanceLaneTest { private static final MethodDescriptor ECHO = - GrpcTextCodec.unary("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcTextCodec.unary("caskeleton.document.v1.DocumentService/GetDocument"); private static final int SAMPLE_SIZE = 200; private static ServerServiceDefinition echoService() { @@ -43,7 +43,7 @@ class GrpcPerformanceLaneTest { observer.onNext(request); observer.onCompleted(); }); - return ServerServiceDefinition.builder("hyeonworks.document.v1.DocumentService") + return ServerServiceDefinition.builder("caskeleton.document.v1.DocumentService") .addMethod(ECHO, handler) .build(); } diff --git a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/release/GrpcStableReleaseGateTest.java b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/release/GrpcStableReleaseGateTest.java deleted file mode 100644 index b5012b5..0000000 --- a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/release/GrpcStableReleaseGateTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package dev.caskeleton.grpc.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.grpc.codegen.GrpcSchemaArtifactPublisher; -import dev.caskeleton.grpc.testkit.GrpcEvidenceGrade; -import java.util.EnumSet; -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 GrpcStableReleaseGateTest { - - private final GrpcStableReleaseGate gate = - new GrpcStableReleaseGate(GrpcCompatibilityMatrix.caSkeleton()); - - private static Map allLanesPassing() { - Map lanes = new LinkedHashMap<>(); - GrpcCompatibilityMatrix.caSkeleton().blockingLanes().forEach(lane -> lanes.put(lane, true)); - return lanes; - } - - private static GrpcReleaseEvidence completeEvidence() { - return new GrpcReleaseEvidence( - GrpcReleaseEvidence.requiredGrades(), - Set.of("tls", "http2", "interceptor-order", "completion-unknown", "latency"), - true, - true, - true); - } - - private static GrpcSchemaArtifactPublisher.PublishDecision schemaAllowed() { - return new GrpcSchemaArtifactPublisher.PublishDecision(true, List.of()); - } - - @Test - @DisplayName("a release with every lane, grade and document approved goes out") - void aCompleteReleaseIsApproved() { - GrpcReleaseDecision decision = - gate.evaluate(completeEvidence(), allLanesPassing(), schemaAllowed()); - - assertThat(decision.approved()).isTrue(); - assertThat(decision.blockers()).isEmpty(); - } - - @Test - @DisplayName("a certified lane that did not run blocks the release") - void aMissingCertifiedLaneBlocks() { - Map missing = allLanesPassing(); - missing.remove("netty-shaded"); - - assertThat(gate.evaluate(completeEvidence(), missing, schemaAllowed()).blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("netty-shaded")); - } - - @Test - @DisplayName("a certified lane that failed blocks the release") - void aFailedCertifiedLaneBlocks() { - Map failed = allLanesPassing(); - failed.put("boot-managed-platform", false); - - assertThat(gate.evaluate(completeEvidence(), failed, schemaAllowed()).blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("boot-managed-platform")); - } - - @Test - @DisplayName("a watch lane's absence does not block") - void watchLanesDoNotBlock() { - assertThat(GrpcCompatibilityMatrix.caSkeleton().blockingLanes()) - .doesNotContain("protobuf-edition-2024", "protobuf-edition-2026"); - assertThat(GrpcCompatibilityMatrix.Lane.WATCH.blocking()).isFalse(); - assertThat(GrpcCompatibilityMatrix.Lane.COMPATIBILITY.blocking()).isFalse(); - assertThat(GrpcCompatibilityMatrix.Lane.CERTIFIED.blocking()).isTrue(); - } - - @Test - @DisplayName("a missing evidence grade blocks and says what it would have certified") - void aMissingGradeBlocks() { - GrpcReleaseEvidence noFaultLane = - new GrpcReleaseEvidence( - EnumSet.of( - GrpcEvidenceGrade.CONTRACT, - GrpcEvidenceGrade.TRANSPORT, - GrpcEvidenceGrade.PERFORMANCE), - Set.of("tls"), - true, - true, - true); - - assertThat(gate.evaluate(noFaultLane, allLanesPassing(), schemaAllowed()).blockers()) - .anySatisfy( - blocker -> assertThat(blocker).contains("FAULT").contains("completion-unknown")); - } - - @Test - @DisplayName("the operational documents are blockers, not follow-ups") - void missingDocumentsBlock() { - GrpcReleaseEvidence undocumented = - new GrpcReleaseEvidence( - GrpcReleaseEvidence.requiredGrades(), Set.of("tls"), false, false, false); - - assertThat(gate.evaluate(undocumented, allLanesPassing(), schemaAllowed()).blockers()) - .anySatisfy(blocker -> assertThat(blocker).contains("runbook")) - .anySatisfy(blocker -> assertThat(blocker).contains("architecture decision records")) - .anySatisfy(blocker -> assertThat(blocker).contains("support matrix")); - } - - @Test - @DisplayName("a schema that breaks a consumer blocks the release") - void aBrokenConsumerBlocks() { - GrpcSchemaArtifactPublisher.PublishDecision refused = - new GrpcSchemaArtifactPublisher.PublishDecision( - false, List.of("consumer 'document-client-v1' loses METHOD_PATH 'CreateDocument'")); - - assertThat(gate.evaluate(completeEvidence(), allLanesPassing(), refused).blockers()) - .anySatisfy(blocker -> assertThat(blocker).startsWith("schema:")); - } - - @Test - @DisplayName("a capability may not be advertised on evidence of the wrong grade") - void aCapabilityNeedsEvidenceOfTheRightGrade() { - GrpcReleaseEvidence contractOnly = - new GrpcReleaseEvidence( - EnumSet.of(GrpcEvidenceGrade.CONTRACT), - Set.of("tls", "interceptor-order"), - true, - true, - true); - - assertThat(contractOnly.supports("interceptor-order")).isTrue(); - assertThat(contractOnly.supports("tls")).isFalse(); - GrpcStableReleaseGate.requireCertified(contractOnly, "interceptor-order"); - assertThatThrownBy(() -> GrpcStableReleaseGate.requireCertified(contractOnly, "tls")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("not certified by the evidence"); - } - - @Test - @DisplayName("a matrix with no certified lane certifies nothing and is refused") - void aMatrixWithNoCertifiedLaneIsRefused() { - assertThatThrownBy( - () -> - new GrpcCompatibilityMatrix( - Map.of("everything", GrpcCompatibilityMatrix.Lane.WATCH))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("certifies nothing"); - } -} diff --git a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcInProcessContractFixtureTest.java b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcInProcessContractFixtureTest.java index b7aa2ec..70eceaf 100644 --- a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcInProcessContractFixtureTest.java +++ b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcInProcessContractFixtureTest.java @@ -24,10 +24,10 @@ class GrpcInProcessContractFixtureTest { private static final MethodDescriptor ECHO = GrpcInProcessContractFixture.unaryMethod( - "hyeonworks.document.v1.DocumentService/GetDocument"); + "caskeleton.document.v1.DocumentService/GetDocument"); private static final MethodDescriptor WATCH = GrpcInProcessContractFixture.streamingMethod( - "hyeonworks.document.v1.DocumentService/WatchDocuments"); + "caskeleton.document.v1.DocumentService/WatchDocuments"); /** Records the order interceptors actually ran in, which is the property under test. */ private record OrderRecordingInterceptor(String name, List log) diff --git a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcNettyContractProfileTest.java b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcNettyContractProfileTest.java index a73358a..bfccd45 100644 --- a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcNettyContractProfileTest.java +++ b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcNettyContractProfileTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; class GrpcNettyContractProfileTest { private static final MethodDescriptor ECHO = - GrpcTextCodec.unary("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcTextCodec.unary("caskeleton.document.v1.DocumentService/GetDocument"); private static ServerServiceDefinition echoService() { ServerCallHandler handler = @@ -34,7 +34,7 @@ class GrpcNettyContractProfileTest { observer.onNext("echo:" + request); observer.onCompleted(); }); - return ServerServiceDefinition.builder("hyeonworks.document.v1.DocumentService") + return ServerServiceDefinition.builder("caskeleton.document.v1.DocumentService") .addMethod(ECHO, handler) .build(); } diff --git a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcPackageOwnershipTest.java b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcPackageOwnershipTest.java index 22a4835..a5f460c 100644 --- a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcPackageOwnershipTest.java +++ b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcPackageOwnershipTest.java @@ -17,7 +17,7 @@ class GrpcPackageOwnershipTest { @Test void corePolicyAndLedgerJpaDoNotSplitAJavaPackageAcrossLeaves() throws Exception { Path repo = repositoryRoot(); - List leaves = List.of("grpc-core-api", "grpc-policy", "grpc-operation-ledger-jpa"); + List leaves = List.of("grpc-core-api", "grpc-runtime", "grpc-operation-ledger-jpa"); Map> owners = new LinkedHashMap<>(); for (String leaf : leaves) { Path source = repo.resolve("src/grpc").resolve(leaf).resolve("src/main/java"); diff --git a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcTransportEvidenceClassifierTest.java b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcTransportEvidenceClassifierTest.java index 3b7c224..41ef53e 100644 --- a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcTransportEvidenceClassifierTest.java +++ b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcTransportEvidenceClassifierTest.java @@ -40,9 +40,9 @@ import org.junit.jupiter.api.Test; class GrpcTransportEvidenceClassifierTest { private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final MethodDescriptor CREATE_DESCRIPTOR = GrpcTextCodec.unary(CREATE.canonical()); private static final MethodDescriptor GET_DESCRIPTOR = @@ -349,7 +349,7 @@ class GrpcTransportEvidenceClassifierTest { return GrpcNettyTestServer.start( GrpcNettyContractProfile.plaintext(), List.of( - ServerServiceDefinition.builder("hyeonworks.document.v1.DocumentService") + ServerServiceDefinition.builder("caskeleton.document.v1.DocumentService") .addMethod(descriptor, handler) .build()), List.of(), diff --git a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcUnaryReliabilityContractTest.java b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcUnaryReliabilityContractTest.java index 164ff6f..d27214f 100644 --- a/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcUnaryReliabilityContractTest.java +++ b/grpc/grpc-testkit/src/test/java/dev/caskeleton/grpc/testkit/GrpcUnaryReliabilityContractTest.java @@ -21,11 +21,11 @@ import org.junit.jupiter.api.Test; class GrpcUnaryReliabilityContractTest { private static final GrpcMethodName GET = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/GetDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/GetDocument"); private static final GrpcMethodName CREATE = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); private static final GrpcMethodName KEYED = - GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/SubmitOrder"); + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/SubmitOrder"); private final GrpcUnaryReliabilityContract contract = GrpcUnaryReliabilityContract.stable(GET, CREATE, KEYED);