refactor: 백엔드 리펙토링 진행 중

This commit is contained in:
DongHyeonka
2026-09-25 17:57:07 +09:00
parent fd80de369d
commit 2c7d1d58f3
44 changed files with 315 additions and 1852 deletions
+4 -3
View File
@@ -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와 브리지가 함께 들어간다.
## 테스트 명령
@@ -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.
*
* <p>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.
*
* <p>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<String> 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<String> 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.");
}
}
}
@@ -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.
*
* <p>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.
*
* <p>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<String> modules) {
private static final Set<String> 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<String> 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<String> 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}.
*
* <p>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<String> advancedLeaks(Set<String> candidateDependencies) {
Set<String> leaks = new LinkedHashSet<>(candidateDependencies);
leaks.retainAll(ADVANCED);
return Set.copyOf(leaks);
}
}
@@ -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<String> registered =
entry
.matcher(registry)
.results()
.map(result -> result.group(1))
.collect(java.util.stream.Collectors.toUnmodifiableSet());
Set<String> 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<String> 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"));
}
}
@@ -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.
*
* <p>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.
*
* <p>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<String> 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<String> 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<String> forbiddenPackagePrefixes() {
return FORBIDDEN_PREFIXES;
}
/** The forbidden exact types. */
public static Set<String> 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<String> violations(String adapterName, Set<String> 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<String> 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);
}
}
@@ -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.
*
* <p>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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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 + "."));
}
}
@@ -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.
*
* <p>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.
*
* <p>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 {};
}
@@ -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<String> 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);
}
}
@@ -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.
*
* <p>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.
* <p>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. */
@@ -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);
}
}
@@ -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
* <p>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<String> violations(
GrpcPlatformProperties properties,
GrpcMethodPolicyCatalog catalog,
List<GrpcNamedChannelProfile> channelProfiles,
Set<String> stableModuleDependencies) {
if (properties == null
|| catalog == null
|| channelProfiles == null
|| stableModuleDependencies == null) {
List<GrpcNamedChannelProfile> channelProfiles) {
if (properties == null || catalog == null || channelProfiles == null) {
throw new IllegalArgumentException("startup validation needs every input");
}
List<String> 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<GrpcNamedChannelProfile> channelProfiles,
Set<String> stableModuleDependencies) {
List<String> violations =
violations(properties, catalog, channelProfiles, stableModuleDependencies);
List<GrpcNamedChannelProfile> channelProfiles) {
List<String> 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<String> stableModuleDependencies, List<String> violations) {
try {
GrpcStableBuildInvariant.requireNoAdvancedDependency(
"grpc-spring-boot-starter", stableModuleDependencies);
} catch (IllegalStateException leaked) {
violations.add(leaked.getMessage());
}
}
private static List<GrpcMethodName> sorted(Set<GrpcMethodName> methods) {
return methods.stream()
.sorted(java.util.Comparator.comparing(GrpcMethodName::canonical))
@@ -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 =
@@ -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<String> 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<String> 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 ->