From 2c7d1d58f3a5837ec4e3f1c8e7a49231a962bf78 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 25 Sep 2026 17:57:07 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20=EB=B0=B1=EC=97=94=EB=93=9C=20?= =?UTF-8?q?=EB=A6=AC=ED=8E=99=ED=86=A0=EB=A7=81=20=EC=A7=84=ED=96=89=20?= =?UTF-8?q?=EC=A4=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../grpc-advanced-support-matrix.md | 14 +- docs/runbooks/grpc-advanced-capabilities.md | 19 +- grpc-advanced/CLAUDE.md | 17 +- .../bootstrap/GrpcAdvancedModuleGuard.java | 20 -- .../GrpcAdvancedModuleGuardTest.java | 15 -- .../grpc-advanced-compat/build.gradle | 11 +- .../kotlin/GrpcKotlinCompatibilityGate.java | 69 ------- .../advanced/kotlin/GrpcKotlinProfile.java | 35 ---- .../servlet/GrpcServletCapabilityMatrix.java | 50 ----- .../GrpcServletCompatibilityProfile.java | 51 ----- .../servlet/GrpcServletStartupValidator.java | 51 ----- .../web/GrpcWebCompatibilityGate.java | 56 ------ ...va => GrpcCoroutineContextBridgeTest.java} | 35 +--- .../GrpcServletStartupValidatorTest.java | 79 -------- ...est.java => GrpcWebCompatibilityTest.java} | 24 +-- .../grpc-advanced-diagnostics/build.gradle | 3 +- .../GrpcAdvancedInfrastructureTestkit.java | 87 -------- .../GrpcChannelDiagnosticsPolicyTest.java | 30 --- .../grpc-advanced-edition/build.gradle | 2 +- .../advanced/edition/GrpcEdition2024Gate.java | 61 ------ .../edition/GrpcEdition2026Guard.java | 48 ----- .../proto/edition2024/compatibility.proto | 2 +- ...st.java => GrpcEdition2024PolicyTest.java} | 23 +-- ...va => GrpcEdition2026WatchReportTest.java} | 37 +--- .../discovery/GrpcResolverSafetyPolicy.java | 68 ++++--- .../discovery/GrpcResolverUpdate.java | 21 +- .../advanced/xds/GrpcXdsStartupGuard.java | 100 ---------- .../GrpcResolverSafetyPolicyTest.java | 58 +++++- .../resilience/GrpcXdsProfileTest.java | 94 +++++++++ .../resilience/GrpcXdsStartupGuardTest.java | 188 ------------------ .../src/test/resources/xds/bootstrap.json | 40 ---- grpc/CLAUDE.md | 7 +- .../grpc/core/GrpcStableBuildInvariant.java | 53 ----- .../grpc/core/GrpcStableModuleCatalog.java | 79 -------- .../core/GrpcStableModuleCatalogTest.java | 90 --------- .../GrpcApplicationBoundaryRules.java | 92 --------- .../architecture/GrpcRawApiImportRule.java | 108 ---------- .../GrpcServiceAdapterMarker.java | 25 --- .../GrpcApplicationBoundaryRulesTest.java | 142 ------------- .../boot/GrpcPlatformAutoConfiguration.java | 32 +-- .../grpc/boot/GrpcPlatformProperties.java | 20 +- .../boot/GrpcPlatformStartupValidator.java | 39 ++-- ...cPlatformAutoConfigurationContextTest.java | 20 ++ .../GrpcPlatformStartupValidatorTest.java | 52 +---- 44 files changed, 315 insertions(+), 1852 deletions(-) delete mode 100644 grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinCompatibilityGate.java delete mode 100644 grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/kotlin/GrpcKotlinProfile.java delete mode 100644 grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCapabilityMatrix.java delete mode 100644 grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletCompatibilityProfile.java delete mode 100644 grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/servlet/GrpcServletStartupValidator.java delete mode 100644 grpc-advanced/grpc-advanced-compat/src/main/java/dev/caskeleton/grpc/advanced/web/GrpcWebCompatibilityGate.java rename grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/{GrpcKotlinCompatibilityGateTest.java => GrpcCoroutineContextBridgeTest.java} (53%) delete mode 100644 grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/GrpcServletStartupValidatorTest.java rename grpc-advanced/grpc-advanced-compat/src/test/java/dev/caskeleton/grpc/advanced/compat/{GrpcWebCompatibilityGateTest.java => GrpcWebCompatibilityTest.java} (82%) delete mode 100644 grpc-advanced/grpc-advanced-diagnostics/src/main/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcAdvancedInfrastructureTestkit.java delete mode 100644 grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024Gate.java delete mode 100644 grpc-advanced/grpc-advanced-edition/src/main/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2026Guard.java rename grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/{GrpcEdition2024GateTest.java => GrpcEdition2024PolicyTest.java} (78%) rename grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/{GrpcEdition2026GuardTest.java => GrpcEdition2026WatchReportTest.java} (60%) delete mode 100644 grpc-advanced/grpc-advanced-resilience/src/main/java/dev/caskeleton/grpc/advanced/xds/GrpcXdsStartupGuard.java create mode 100644 grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java delete mode 100644 grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsStartupGuardTest.java delete mode 100644 grpc-advanced/grpc-advanced-resilience/src/test/resources/xds/bootstrap.json delete mode 100644 grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableBuildInvariant.java delete mode 100644 grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalog.java delete mode 100644 grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/core/GrpcStableModuleCatalogTest.java delete mode 100644 grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRules.java delete mode 100644 grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcRawApiImportRule.java delete mode 100644 grpc/grpc-server/src/main/java/dev/caskeleton/grpc/architecture/GrpcServiceAdapterMarker.java delete mode 100644 grpc/grpc-server/src/test/java/dev/caskeleton/grpc/architecture/GrpcApplicationBoundaryRulesTest.java diff --git a/docs/compatibility/grpc-advanced-support-matrix.md b/docs/compatibility/grpc-advanced-support-matrix.md index b3cf491..7660104 100644 --- a/docs/compatibility/grpc-advanced-support-matrix.md +++ b/docs/compatibility/grpc-advanced-support-matrix.md @@ -29,7 +29,7 @@ All capabilities are off by default. Flags are `ca-skeleton.grpc.advanced..enabled`이고 전부 | `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 요구사항 | +| `grpc-advanced-compat` | gRPC-Web, Spring Integration bridge, Reactor adapter, Kotlin coroutine 취소 bridge | +| `grpc-advanced-diagnostics` | Channelz/CSDS 진단 | ## Promotion은 capability별로 독립이다 @@ -58,20 +57,20 @@ property key는 `ca-skeleton.grpc.advanced..enabled`이고 전부 ## 이 저장소에서 검증할 수 없는 것 -`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/src/main/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuard.java b/grpc-advanced/grpc-advanced-bootstrap/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-bootstrap/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/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java b/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java index 9f53e67..dcaae0e 100644 --- a/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java +++ b/grpc-advanced/grpc-advanced-bootstrap/src/test/java/dev/caskeleton/grpc/advanced/bootstrap/GrpcAdvancedModuleGuardTest.java @@ -89,21 +89,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-compat/build.gradle b/grpc-advanced/grpc-advanced-compat/build.gradle index 011791e..ec85357 100644 --- a/grpc-advanced/grpc-advanced-compat/build.gradle +++ b/grpc-advanced/grpc-advanced-compat/build.gradle @@ -2,14 +2,11 @@ plugins { id 'ca.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. dependencies { api project(':grpc:grpc-core-api') api project(':grpc:grpc-policy') 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/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 82% 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..0a215f8 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,19 @@ 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 java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; -import java.util.Map; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -class 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 +29,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() { @@ -132,7 +112,7 @@ class GrpcWebCompatibilityGateTest { 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-diagnostics/build.gradle b/grpc-advanced/grpc-advanced-diagnostics/build.gradle index e9cb9d0..be5a1d2 100644 --- a/grpc-advanced/grpc-advanced-diagnostics/build.gradle +++ b/grpc-advanced/grpc-advanced-diagnostics/build.gradle @@ -3,8 +3,7 @@ plugins { } // 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). +// credentials, certificate material, metadata and payload out of a snapshot. dependencies { api project(':grpc:grpc-core-api') api project(':grpc:grpc-client') 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-diagnostics/src/test/java/dev/caskeleton/grpc/advanced/diagnostics/GrpcChannelDiagnosticsPolicyTest.java b/grpc-advanced/grpc-advanced-diagnostics/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-diagnostics/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-edition/build.gradle b/grpc-advanced/grpc-advanced-edition/build.gradle index bbf33e2..f85d0e8 100644 --- a/grpc-advanced/grpc-advanced-edition/build.gradle +++ b/grpc-advanced/grpc-advanced-edition/build.gradle @@ -4,7 +4,7 @@ plugins { // 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. +// release/toolchain status. dependencies { api project(':grpc:grpc-core-api') api project(':grpc:grpc-proto-contract') 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-edition/src/main/resources/proto/edition2024/compatibility.proto b/grpc-advanced/grpc-advanced-edition/src/main/resources/proto/edition2024/compatibility.proto index 40679ad..a01b652 100644 --- a/grpc-advanced/grpc-advanced-edition/src/main/resources/proto/edition2024/compatibility.proto +++ b/grpc-advanced/grpc-advanced-edition/src/main/resources/proto/edition2024/compatibility.proto @@ -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-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024GateTest.java b/grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java similarity index 78% rename from grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024GateTest.java rename to grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024PolicyTest.java index e13d839..79cd037 100644 --- a/grpc-advanced/grpc-advanced-edition/src/test/java/dev/caskeleton/grpc/advanced/edition/GrpcEdition2024GateTest.java +++ b/grpc-advanced/grpc-advanced-edition/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) { @@ -74,25 +74,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 +87,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-edition/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-edition/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-edition/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/main/java/dev/caskeleton/grpc/advanced/discovery/GrpcResolverSafetyPolicy.java b/grpc-advanced/grpc-advanced-resilience/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-resilience/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-resilience/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-resilience/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-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/GrpcResolverSafetyPolicyTest.java b/grpc-advanced/grpc-advanced-resilience/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-resilience/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-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java b/grpc-advanced/grpc-advanced-resilience/src/test/java/dev/caskeleton/grpc/advanced/resilience/GrpcXdsProfileTest.java new file mode 100644 index 0000000..6d2ffd7 --- /dev/null +++ b/grpc-advanced/grpc-advanced-resilience/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("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("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-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/CLAUDE.md b/grpc/CLAUDE.md index 766fb78..604eb24 100644 --- a/grpc/CLAUDE.md +++ b/grpc/CLAUDE.md @@ -67,7 +67,7 @@ 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에 있다는 것의 의미 @@ -88,8 +88,9 @@ soak/performance baseline을 자동으로 의미하지 않는다. 지원 범위 application-owned port → adapter:inbound:grpc (typed service adapter) → :grpc:grpc-server 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-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/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-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/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..6e57e6b 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,11 @@ 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; @@ -80,16 +80,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,9 +123,9 @@ 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 and + * named client channels. */ @Bean public SmartInitializingSingleton grpcPlatformStartupCheck( @@ -129,8 +136,7 @@ public class GrpcPlatformAutoConfiguration { GrpcPlatformStartupValidator.requireValid( properties, catalogs.getIfAvailable(() -> GrpcMethodPolicyCatalog.builder().build()), - channelProfiles.orderedStream().toList(), - Set.of()); + channelProfiles.orderedStream().toList()); } /** 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..92c5be0 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 @@ -22,8 +22,12 @@ 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..24cf787 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,7 +6,6 @@ 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; @@ -33,20 +32,17 @@ 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) { + List channelProfiles) { + if (properties == null || catalog == null || channelProfiles == null) { throw new IllegalArgumentException("startup validation needs every input"); } List violations = new ArrayList<>(); @@ -55,7 +51,6 @@ public final class GrpcPlatformStartupValidator { validateExecutor(properties, violations); validateMethods(properties, catalog, violations); validateChannels(channelProfiles, violations); - validateAdvancedIsolation(stableModuleDependencies, violations); return List.copyOf(violations); } @@ -67,10 +62,8 @@ public final class GrpcPlatformStartupValidator { public static void requireValid( GrpcPlatformProperties properties, GrpcMethodPolicyCatalog catalog, - List channelProfiles, - Set stableModuleDependencies) { - List violations = - violations(properties, catalog, channelProfiles, stableModuleDependencies); + List channelProfiles) { + List violations = violations(properties, catalog, channelProfiles); if (!violations.isEmpty()) { throw new GrpcPlatformConfigurationException(violations); } @@ -84,6 +77,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( + "ca-skeleton.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"); @@ -172,16 +171,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..e328acd 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; @@ -26,6 +27,25 @@ class GrpcPlatformAutoConfigurationContextTest { .hasMessageContaining("providing none"); } + @Test + void enabledPlatformWithoutAnEnvironmentRefusesToStartInsteadOfAssumingLocal() { + // when + Throwable failure = + catchThrowable( + () -> + start( + Map.of( + "ca-skeleton.grpc.platform.enabled", "true", + "ca-skeleton.grpc.platform.transport", "NETTY_SHADED", + "ca-skeleton.grpc.platform.tls-enabled", "false", + "ca-skeleton.grpc.platform.reflection-mode", "ENABLED"))); + + // then + assertThat(failure) + .isInstanceOf(GrpcPlatformConfigurationException.class) + .hasMessageContaining("ca-skeleton.grpc.platform.environment is not set"); + } + @Test void coherentLocalConfigurationRunsTheStartupValidatorAndStarts() { try (AnnotationConfigApplicationContext context = 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..aaa4c26 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 @@ -23,7 +23,6 @@ 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; @@ -36,9 +35,6 @@ class GrpcPlatformStartupValidatorTest { 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); @@ -73,10 +69,10 @@ class GrpcPlatformStartupValidatorTest { void aCoherentConfigurationStarts() { assertThat( GrpcPlatformStartupValidator.violations( - productionProperties(), healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + productionProperties(), healthyCatalog(), oneChannel())) .isEmpty(); GrpcPlatformStartupValidator.requireValid( - productionProperties(), healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES); + productionProperties(), healthyCatalog(), oneChannel()); } @Test @@ -91,9 +87,7 @@ class GrpcPlatformStartupValidatorTest { GrpcPlatformProperties properties = productionProperties(); properties.setTransport(GrpcServerTransport.IN_PROCESS); - assertThat( - GrpcPlatformStartupValidator.violations( - properties, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + assertThat(GrpcPlatformStartupValidator.violations(properties, healthyCatalog(), oneChannel())) .anySatisfy(violation -> assertThat(violation).contains("not network evidence")); } @@ -105,13 +99,9 @@ class GrpcPlatformStartupValidatorTest { GrpcPlatformProperties trustAll = productionProperties(); trustAll.setTrustAllCertificates(true); - assertThat( - GrpcPlatformStartupValidator.violations( - noTls, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + assertThat(GrpcPlatformStartupValidator.violations(noTls, healthyCatalog(), oneChannel())) .anySatisfy(violation -> assertThat(violation).contains("TLS is required")); - assertThat( - GrpcPlatformStartupValidator.violations( - trustAll, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + assertThat(GrpcPlatformStartupValidator.violations(trustAll, healthyCatalog(), oneChannel())) .anySatisfy(violation -> assertThat(violation).contains("providing none")); } @@ -121,9 +111,7 @@ class GrpcPlatformStartupValidatorTest { GrpcPlatformProperties properties = productionProperties(); properties.setReflectionMode(GrpcReflectionMode.ENABLED); - assertThat( - GrpcPlatformStartupValidator.violations( - properties, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + assertThat(GrpcPlatformStartupValidator.violations(properties, healthyCatalog(), oneChannel())) .anySatisfy(violation -> assertThat(violation).contains("published to anyone")); assertThat(productionProperties().effectiveReflectionMode()) .isEqualTo(GrpcReflectionMode.DISABLED); @@ -135,9 +123,7 @@ class GrpcPlatformStartupValidatorTest { GrpcPlatformProperties properties = productionProperties(); properties.setExecutorQueueCapacity(0); - assertThat( - GrpcPlatformStartupValidator.violations( - properties, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + assertThat(GrpcPlatformStartupValidator.violations(properties, healthyCatalog(), oneChannel())) .anySatisfy(violation -> assertThat(violation).contains("unbounded latency")); } @@ -160,9 +146,7 @@ class GrpcPlatformStartupValidatorTest { 1024)) .build(); - assertThat( - GrpcPlatformStartupValidator.violations( - properties, catalog, oneChannel(), STABLE_DEPENDENCIES)) + assertThat(GrpcPlatformStartupValidator.violations(properties, catalog, oneChannel())) .anySatisfy(violation -> assertThat(violation).contains("never honoured")); } @@ -184,8 +168,7 @@ class GrpcPlatformStartupValidatorTest { .build(); assertThat( - GrpcPlatformStartupValidator.violations( - productionProperties(), catalog, oneChannel(), STABLE_DEPENDENCIES)) + GrpcPlatformStartupValidator.violations(productionProperties(), catalog, oneChannel())) .anySatisfy(violation -> assertThat(violation).contains("Advanced capability")); } @@ -207,21 +190,10 @@ class GrpcPlatformStartupValidatorTest { assertThat( GrpcPlatformStartupValidator.violations( - productionProperties(), healthyCatalog(), twoOwners, STABLE_DEPENDENCIES)) + productionProperties(), healthyCatalog(), twoOwners)) .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() { @@ -231,9 +203,7 @@ class GrpcPlatformStartupValidatorTest { broken.setExecutorQueueCapacity(0); assertThatThrownBy( - () -> - GrpcPlatformStartupValidator.requireValid( - broken, healthyCatalog(), oneChannel(), STABLE_DEPENDENCIES)) + () -> GrpcPlatformStartupValidator.requireValid(broken, healthyCatalog(), oneChannel())) .isInstanceOf(GrpcPlatformConfigurationException.class) .satisfies( failure ->