feat: grpc 기능 deep 구현

This commit is contained in:
DongHyeonka
2026-08-31 07:28:39 +09:00
commit 41c2c5ac34
395 changed files with 32985 additions and 0 deletions
@@ -0,0 +1,43 @@
package dev.caskeleton.grpc.codegen;
/**
* The Buf breaking-change categories, ordered from strictest to loosest.
*
* <p>The Stable gate is {@link #FILE}, and the reason is the pair of properties below: only FILE
* and PACKAGE detect a change that keeps the wire format identical while breaking every generated
* consumer's compile. A team that gates on WIRE ships a field rename, watches its own integration
* tests pass, and finds out at the consumer's next build.
*/
public enum GrpcBreakingCategory {
/** Strictest: also catches file moves, package moves and Java option changes. */
FILE(true, true),
/** Catches type and field source breaks within a package, but not a file move. */
PACKAGE(true, false),
/** Wire plus JSON name compatibility. Source breaks pass. */
WIRE_JSON(false, false),
/** Binary wire compatibility only. Source breaks pass. */
WIRE(false, false);
private final boolean detectsSourceBreak;
private final boolean detectsFileMove;
GrpcBreakingCategory(boolean detectsSourceBreak, boolean detectsFileMove) {
this.detectsSourceBreak = detectsSourceBreak;
this.detectsFileMove = detectsFileMove;
}
/** Whether this category fails a change that stops a generated consumer compiling. */
public boolean detectsSourceBreak() {
return detectsSourceBreak;
}
/** Whether this category fails a file or package relocation. */
public boolean detectsFileMove() {
return detectsFileMove;
}
/** The category the Stable public API is gated on. */
public static GrpcBreakingCategory stableGate() {
return FILE;
}
}
@@ -0,0 +1,75 @@
package dev.caskeleton.grpc.codegen;
import java.util.List;
import java.util.Set;
/**
* The schema governance this repository runs, as a value the build and the tests both read.
*
* <p>Buf's CLI is not part of this toolchain (adaptation D5), so the four lifecycle task names
* below are the contract a CI environment fulfils and {@code GrpcProtoContractValidator} is what
* actually fails a build here. Keeping the task names in the policy rather than only in a workflow
* file means a missing stage is a test failure rather than a stage nobody noticed was gone.
*/
public record GrpcBufPolicy(
GrpcBreakingCategory breakingCategory,
boolean formatEnforced,
boolean lintEnforced,
GrpcSchemaBaseline baseline) {
/** The lifecycle stages a compliant schema pipeline runs, in order. */
private static final List<String> REQUIRED_TASKS =
List.of("bufFormatCheck", "bufLint", "bufBuild", "bufBreaking");
/** Refuses a policy that would let a source break through. */
public GrpcBufPolicy {
if (breakingCategory == null) {
throw new IllegalArgumentException("a Buf policy needs a breaking category");
}
if (baseline == null) {
throw new IllegalArgumentException(
"a Buf policy needs a released baseline to compare against");
}
if (!breakingCategory.detectsSourceBreak()) {
throw new IllegalArgumentException(
"the Stable public API may not be gated on "
+ breakingCategory
+ ": wire compatibility alone lets a rename through as compatible while every "
+ "generated consumer stops compiling");
}
if (!formatEnforced || !lintEnforced) {
throw new IllegalArgumentException(
"format and lint are not optional; a schema that is not linted is a schema whose style "
+ "rules are whatever the last author preferred");
}
}
/** The Stable policy: FILE breaking, format and lint enforced. */
public static GrpcBufPolicy stable(GrpcSchemaBaseline baseline) {
return new GrpcBufPolicy(GrpcBreakingCategory.stableGate(), true, true, baseline);
}
/** The lifecycle task names a compliant pipeline registers. */
public static List<String> requiredTasks() {
return REQUIRED_TASKS;
}
/**
* The task names missing from {@code registeredTasks}.
*
* @return an empty set when the pipeline is complete
*/
public static Set<String> missingTasks(Set<String> registeredTasks) {
if (registeredTasks == null) {
throw new IllegalArgumentException("the registered task set must not be null");
}
return REQUIRED_TASKS.stream()
.filter(task -> !registeredTasks.contains(task))
.collect(java.util.stream.Collectors.toUnmodifiableSet());
}
/** Whether a candidate schema hash may be released without a breaking review. */
public boolean unchangedFromBaseline(String candidateSchemaHash) {
return baseline.matches(candidateSchemaHash);
}
}
@@ -0,0 +1,81 @@
package dev.caskeleton.grpc.codegen;
/**
* Who generates Java from the schema, with what versions, into where.
*
* <p>One owner, named. Two generators for one schema is the state in which a type exists twice with
* different options and the classpath decides which one a consumer gets; refusing a second owner is
* cheaper than diagnosing that.
*
* <p>Both version sources are required to be the managed BOM rather than a literal. A pinned
* protobuf version beside a BOM-managed gRPC version is how the runtime and the generator drift
* into a combination nobody tested, and the symptom is a {@code NoSuchMethodError} in generated
* code.
*/
public record GrpcCodegenManifest(
String codegenOwner,
String protobufVersionSource,
String grpcJavaVersionSource,
GrpcCodegenOutput output,
GrpcGeneratedPackagePolicy packagePolicy) {
/** The only accepted version source: whatever the build's managed platform resolves. */
public static final String MANAGED_VERSION_SOURCE = "managed-platform";
/** Refuses a second owner, a literal version, or overlapping package namespaces. */
public GrpcCodegenManifest {
if (codegenOwner == null || codegenOwner.isBlank()) {
throw new IllegalArgumentException("code generation needs exactly one named owner");
}
if (output == null || packagePolicy == null) {
throw new IllegalArgumentException("a codegen manifest needs an output and a package policy");
}
requireManagedVersion(protobufVersionSource, "protobuf");
requireManagedVersion(grpcJavaVersionSource, "grpc-java");
packagePolicy.requireDisjoint();
}
private static void requireManagedVersion(String source, String what) {
if (!MANAGED_VERSION_SOURCE.equals(source)) {
throw new IllegalArgumentException(
what
+ " version must come from the managed platform, not from a literal declaration; got '"
+ source
+ "'. A pinned generator beside a managed runtime is a combination nobody tested.");
}
}
/**
* This repository's manifest.
*
* <p>The owner is the Gradle protobuf plugin. It does not run in this build yet — adaptation D6
* records why, and this manifest is what a future decision to turn it on has to satisfy rather
* than replace.
*/
public static GrpcCodegenManifest caSkeleton() {
return new GrpcCodegenManifest(
"gradle-protobuf-plugin",
MANAGED_VERSION_SOURCE,
MANAGED_VERSION_SOURCE,
GrpcCodegenOutput.standard(),
new GrpcGeneratedPackagePolicy(
java.util.Set.of("dev.caskeleton"),
java.util.Set.of("hyeonworks.grpc.common.v1.generated")));
}
/**
* Fails when a second generator claims the same schema.
*
* @throws IllegalStateException when {@code otherOwner} is not this manifest's owner
*/
public void requireSoleOwner(String otherOwner) {
if (!codegenOwner.equals(otherOwner)) {
throw new IllegalStateException(
"Java code generation for this schema is owned by '"
+ codegenOwner
+ "'; '"
+ otherOwner
+ "' may not also generate it");
}
}
}
@@ -0,0 +1,58 @@
package dev.caskeleton.grpc.codegen;
/**
* Where generated artifacts land.
*
* <p>Everything here is required to be inside a build directory. A generator that writes into a
* source tree produces files that get committed, then edited, then silently reverted by the next
* regeneration — and the diff that reverts them looks like the generator working correctly.
*/
public record GrpcCodegenOutput(
String javaOutputDirectory,
String grpcJavaOutputDirectory,
String descriptorSetPath,
boolean includeSourceInfo) {
private static final String BUILD_ROOT = "build/";
/** Requires every path to be build-directory relative. */
public GrpcCodegenOutput {
requireBuildRelative(javaOutputDirectory, "java output directory");
requireBuildRelative(grpcJavaOutputDirectory, "grpc-java output directory");
requireBuildRelative(descriptorSetPath, "descriptor set path");
if (!descriptorSetPath.endsWith(".desc") && !descriptorSetPath.endsWith(".binpb")) {
throw new IllegalArgumentException(
"a descriptor set is a serialized FileDescriptorSet; expected a .desc or .binpb path, got '"
+ descriptorSetPath
+ "'");
}
}
private static void requireBuildRelative(String path, String what) {
if (path == null || path.isBlank()) {
throw new IllegalArgumentException(what + " must not be blank");
}
if (path.startsWith("/") || path.contains("..")) {
throw new IllegalArgumentException(
what + " must be a project-relative path without '..'; got '" + path + "'");
}
if (!path.startsWith(BUILD_ROOT)) {
throw new IllegalArgumentException(
what
+ " must be under '"
+ BUILD_ROOT
+ "'; generated sources in a source tree get committed and then edited. Got '"
+ path
+ "'");
}
}
/** This repository's layout. */
public static GrpcCodegenOutput standard() {
return new GrpcCodegenOutput(
"build/generated/source/proto/main/java",
"build/generated/source/proto/main/grpc",
"build/generated/descriptor/stable-schema.desc",
true);
}
}
@@ -0,0 +1,158 @@
package dev.caskeleton.grpc.codegen;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* A previously released consumer, described by exactly what it compiles against.
*
* <p>This is the check a wire-compatibility gate cannot make. A field rename, a service move to a
* new package, or a change to {@code java_package} keeps every serialized message valid and stops
* every generated client compiling — and the only way to notice before the consumer does is to keep
* a record of what the consumer names and compare a candidate schema against it.
*/
public record GrpcConsumerFixture(
String name,
String schemaVersion,
Set<String> requiredServicePaths,
Set<String> requiredMethodPaths,
Set<String> requiredJavaPackages) {
/** What kind of source break a consumer hit. Reported separately, never merged into one count. */
public enum BreakKind {
/** A service the consumer names is gone or moved. */
SERVICE_PATH,
/** A method the consumer calls is gone or renamed. */
METHOD_PATH,
/** The Java package the consumer imports from moved. */
JAVA_PACKAGE
}
/** One thing a consumer needs that a candidate schema no longer provides. */
public record SourceBreak(BreakKind kind, String missing) {
/** Requires both halves. */
public SourceBreak {
if (kind == null || missing == null || missing.isBlank()) {
throw new IllegalArgumentException("a source break names its kind and what went missing");
}
}
}
/** Copies every requirement set. */
public GrpcConsumerFixture {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("a consumer fixture needs a name");
}
if (schemaVersion == null || schemaVersion.isBlank()) {
throw new IllegalArgumentException(
"a consumer fixture names the schema version it was built against");
}
if (requiredServicePaths == null
|| requiredMethodPaths == null
|| requiredJavaPackages == null) {
throw new IllegalArgumentException("a consumer fixture states all three requirement sets");
}
requiredServicePaths = Set.copyOf(requiredServicePaths);
requiredMethodPaths = Set.copyOf(requiredMethodPaths);
requiredJavaPackages = Set.copyOf(requiredJavaPackages);
}
/**
* Derives a fixture from a released consumer's own source.
*
* <p>Read from the consumer rather than declared beside it, because a hand-written requirement
* list is a second copy of what the client already says and the copy is the one that stops being
* updated. Three rules, all mechanical:
*
* <ul>
* <li>a generated Java package is any package a {@code fixture} class imports from;
* <li>a service is a {@code <Name>Grpc} import, mapped back to {@code <package>.<Name>} with
* the generated-package suffix removed;
* <li>a method is a {@code stub.<name>(} call, mapped to {@code <service>/<UpperCamelName>}.
* </ul>
*
* <p>It is an approximation of compiling the fixture, which is what the plan asks for and what
* ADR-GRPC-002 records this repository cannot do yet. It is a useful approximation because it
* fails on exactly the changes a compile would fail on: a renamed method, a moved service, a
* relocated Java package.
*
* @param generatedPackageSuffix the segment appended to a proto package for generated code, e.g.
* {@code generated}; removed to recover the schema's own service path
*/
public static GrpcConsumerFixture fromJavaSource(
String name, String schemaVersion, String javaSource, String generatedPackageSuffix) {
if (javaSource == null || javaSource.isBlank()) {
throw new IllegalArgumentException("a consumer fixture needs its source text");
}
if (generatedPackageSuffix == null || generatedPackageSuffix.isBlank()) {
throw new IllegalArgumentException("the generated package suffix is required");
}
java.util.Set<String> javaPackages = new LinkedHashSet<>();
java.util.Set<String> servicePaths = new LinkedHashSet<>();
java.util.regex.Matcher imports =
java.util.regex.Pattern.compile(
"^\\s*import\\s+([\\w.]+)\\.(\\w+);", java.util.regex.Pattern.MULTILINE)
.matcher(javaSource);
while (imports.find()) {
String importedPackage = imports.group(1);
String importedType = imports.group(2);
if (!importedPackage.endsWith("." + generatedPackageSuffix)) {
continue;
}
javaPackages.add(importedPackage);
if (importedType.endsWith("Grpc")) {
String protoPackage =
importedPackage.substring(
0, importedPackage.length() - generatedPackageSuffix.length() - 1);
servicePaths.add(
protoPackage
+ "."
+ importedType.substring(0, importedType.length() - "Grpc".length()));
}
}
java.util.Set<String> methodPaths = new LinkedHashSet<>();
java.util.regex.Matcher calls =
java.util.regex.Pattern.compile("\\bstub\\.(\\w+)\\s*\\(").matcher(javaSource);
while (calls.find()) {
String method = calls.group(1);
String upperCamel = Character.toUpperCase(method.charAt(0)) + method.substring(1);
servicePaths.forEach(service -> methodPaths.add(service + "/" + upperCamel));
}
if (servicePaths.isEmpty() || methodPaths.isEmpty()) {
throw new IllegalArgumentException(
"no service or method could be derived from '"
+ name
+ "'; a fixture that requires nothing cannot detect a break");
}
return new GrpcConsumerFixture(name, schemaVersion, servicePaths, methodPaths, javaPackages);
}
/**
* What this consumer would fail to compile against {@code candidate}.
*
* @return an empty list when the consumer still compiles
*/
public List<SourceBreak> breaksAgainst(GrpcDescriptorArtifact candidate) {
if (candidate == null) {
throw new IllegalArgumentException("a compatibility check needs a candidate artifact");
}
List<SourceBreak> breaks = new ArrayList<>();
collect(breaks, BreakKind.SERVICE_PATH, requiredServicePaths, candidate.servicePaths());
collect(breaks, BreakKind.METHOD_PATH, requiredMethodPaths, candidate.methodPaths());
collect(
breaks, BreakKind.JAVA_PACKAGE, requiredJavaPackages, candidate.generatedJavaPackages());
return List.copyOf(breaks);
}
private static void collect(
List<SourceBreak> breaks, BreakKind kind, Set<String> required, Set<String> available) {
Set<String> missing = new LinkedHashSet<>(required);
missing.removeAll(available);
missing.stream().sorted().forEach(entry -> breaks.add(new SourceBreak(kind, entry)));
}
}
@@ -0,0 +1,59 @@
package dev.caskeleton.grpc.codegen;
import java.util.Set;
/**
* One immutable release of the schema: what it contains, and the hashes that prove which bytes it
* was built from.
*
* <p>Service and method paths are carried explicitly, not derived on demand, because they are what
* a consumer compatibility check compares. A descriptor that only carries a digest can say
* "something changed" and nothing else, which is the answer least useful to the person who has to
* decide whether to release.
*/
public record GrpcDescriptorArtifact(
String schemaVersion,
String schemaHash,
String descriptorSetDigest,
String bufImageDigest,
String policyVersion,
Set<String> servicePaths,
Set<String> methodPaths,
Set<String> generatedJavaPackages) {
/** Requires an immutable version, three digests and a non-empty surface. */
public GrpcDescriptorArtifact {
if (schemaVersion == null || schemaVersion.isBlank() || schemaVersion.endsWith("-SNAPSHOT")) {
throw new IllegalArgumentException(
"a schema artifact publishes an immutable version; got '" + schemaVersion + "'");
}
requireDigest(schemaHash, "schema hash");
requireDigest(descriptorSetDigest, "descriptor set digest");
requireDigest(bufImageDigest, "buf image digest");
if (policyVersion == null || policyVersion.isBlank()) {
throw new IllegalArgumentException(
"a schema artifact records the policy version it was judged under");
}
if (servicePaths == null || methodPaths == null || generatedJavaPackages == null) {
throw new IllegalArgumentException(
"a schema artifact carries its service, method and package surface");
}
if (methodPaths.isEmpty()) {
throw new IllegalArgumentException("a schema artifact with no methods describes nothing");
}
servicePaths = Set.copyOf(servicePaths);
methodPaths = Set.copyOf(methodPaths);
generatedJavaPackages = Set.copyOf(generatedJavaPackages);
}
private static void requireDigest(String digest, String what) {
if (digest == null || !digest.startsWith("sha256:") || digest.length() < 15) {
throw new IllegalArgumentException(what + " must be 'sha256:<digest>'; got '" + digest + "'");
}
}
/** Whether this artifact is byte-identical to {@code baseline}. */
public boolean unchangedFrom(GrpcSchemaBaseline baseline) {
return baseline.matches(schemaHash);
}
}
@@ -0,0 +1,68 @@
package dev.caskeleton.grpc.codegen;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Keeps generated Java packages and hand-written ones apart.
*
* <p>An overlap is not a style problem. Generated code is deleted and rewritten on every build, so
* a hand-written class that shares its package is one clean build away from being either
* overwritten or, more often, from making the generator's output unbuildable in a way that reads as
* a compiler bug. Splitting the namespaces makes the ownership of every file legible from its
* package alone.
*/
public record GrpcGeneratedPackagePolicy(
Set<String> handWrittenPackages, Set<String> generatedPackages) {
/** Copies both sets. */
public GrpcGeneratedPackagePolicy {
if (handWrittenPackages == null || generatedPackages == null) {
throw new IllegalArgumentException("both package sets must be present");
}
if (generatedPackages.isEmpty()) {
throw new IllegalArgumentException("a codegen policy names at least one generated package");
}
handWrittenPackages = Set.copyOf(handWrittenPackages);
generatedPackages = Set.copyOf(generatedPackages);
}
/**
* Every overlap between the two namespaces, described.
*
* @return an empty list when the namespaces are disjoint
*/
public List<String> overlaps() {
List<String> overlaps = new ArrayList<>();
for (String generated : generatedPackages) {
for (String handWritten : handWrittenPackages) {
if (generated.equals(handWritten)
|| generated.startsWith(handWritten + ".")
|| handWritten.startsWith(generated + ".")) {
overlaps.add(
"generated package '"
+ generated
+ "' overlaps hand-written package '"
+ handWritten
+ "'");
}
}
}
overlaps.sort(java.util.Comparator.naturalOrder());
return List.copyOf(overlaps);
}
/**
* Fails when the namespaces overlap.
*
* @throws IllegalStateException naming every overlap
*/
public void requireDisjoint() {
List<String> overlaps = overlaps();
if (!overlaps.isEmpty()) {
throw new IllegalStateException(
"generated and hand-written Java packages must be disjoint: " + overlaps);
}
}
}
@@ -0,0 +1,113 @@
package dev.caskeleton.grpc.codegen;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Decides whether a candidate schema may be published, and refuses to let a released version change
* underneath its consumers.
*
* <p>Two rules, and the second is the one that gets skipped in a hurry: a consumer fixture that no
* longer compiles blocks the release. Publishing anyway and telling the consumers is not the same
* thing — by then the artifact exists, somebody has resolved it, and the fix is a new version
* rather than a decision not to make the change.
*/
public final class GrpcSchemaArtifactPublisher {
private final GrpcBufPolicy policy;
private final Map<String, String> publishedHashesByVersion = new LinkedHashMap<>();
/** Binds a publisher to the governance policy it enforces. */
public GrpcSchemaArtifactPublisher(GrpcBufPolicy policy) {
if (policy == null) {
throw new IllegalArgumentException("a publisher needs a Buf policy");
}
this.policy = policy;
}
/** Whether a candidate may be published, and if not, why not. */
public record PublishDecision(boolean allowed, List<String> blockers) {
/** Copies the blocker list. */
public PublishDecision {
if (blockers == null) {
throw new IllegalArgumentException(
"a publish decision lists its blockers, even when empty");
}
blockers = List.copyOf(blockers);
if (allowed && !blockers.isEmpty()) {
throw new IllegalArgumentException("an allowed publish has no blockers");
}
if (!allowed && blockers.isEmpty()) {
throw new IllegalArgumentException("a refused publish says why");
}
}
}
/**
* Evaluates a candidate against the policy and every consumer fixture.
*
* @param fixtures the previously released consumers this schema must keep compiling
*/
public PublishDecision evaluate(
GrpcDescriptorArtifact candidate, List<GrpcConsumerFixture> fixtures) {
if (candidate == null || fixtures == null) {
throw new IllegalArgumentException("evaluation needs a candidate and a fixture list");
}
List<String> blockers = new ArrayList<>();
String alreadyPublished = publishedHashesByVersion.get(candidate.schemaVersion());
if (alreadyPublished != null && !alreadyPublished.equals(candidate.schemaHash())) {
blockers.add(
"version '"
+ candidate.schemaVersion()
+ "' is already published with a different schema hash; a released schema version is "
+ "immutable");
}
if (!policy.breakingCategory().detectsSourceBreak()) {
blockers.add("the active breaking category does not detect source breaks");
}
for (GrpcConsumerFixture fixture : fixtures) {
for (GrpcConsumerFixture.SourceBreak sourceBreak : fixture.breaksAgainst(candidate)) {
blockers.add(
"consumer '"
+ fixture.name()
+ "' ("
+ fixture.schemaVersion()
+ ") loses "
+ sourceBreak.kind()
+ " '"
+ sourceBreak.missing()
+ "'");
}
}
return new PublishDecision(blockers.isEmpty(), blockers);
}
/**
* Records a successful publish.
*
* @throws IllegalStateException when the decision refused it
*/
public void publish(GrpcDescriptorArtifact candidate, PublishDecision decision) {
if (decision == null || !decision.allowed()) {
throw new IllegalStateException(
"refusing to publish '"
+ (candidate == null ? "null" : candidate.schemaVersion())
+ "': "
+ (decision == null ? "no decision" : decision.blockers()));
}
publishedHashesByVersion.put(candidate.schemaVersion(), candidate.schemaHash());
}
/** The hash published for {@code version}, or null when nothing was. */
public String publishedHash(String version) {
return publishedHashesByVersion.get(version);
}
/** The governance policy in force. */
public GrpcBufPolicy policy() {
return policy;
}
}
@@ -0,0 +1,37 @@
package dev.caskeleton.grpc.codegen;
import java.time.Instant;
/**
* The released schema a breaking check compares against.
*
* <p>Pinned to a released artifact rather than to a branch, and that is the whole point. Comparing
* against the previous commit answers "did this commit break anything", which is not the question:
* a breaking change introduced two commits ago and refined since then passes every commit-to-commit
* check while being broken against everything that has actually been deployed.
*/
public record GrpcSchemaBaseline(String version, String schemaHash, Instant releasedAt) {
/** Requires an immutable version, a hash and a release moment. */
public GrpcSchemaBaseline {
if (version == null || version.isBlank()) {
throw new IllegalArgumentException("a schema baseline needs a released version");
}
if (version.endsWith("-SNAPSHOT")) {
throw new IllegalArgumentException(
"a breaking baseline must be an immutable release, not '" + version + "'");
}
if (schemaHash == null || !schemaHash.startsWith("sha256:") || schemaHash.length() < 15) {
throw new IllegalArgumentException(
"a schema baseline needs a 'sha256:<digest>' hash; got '" + schemaHash + "'");
}
if (releasedAt == null) {
throw new IllegalArgumentException("a schema baseline needs a release timestamp");
}
}
/** Whether {@code candidateHash} is byte-identical to this baseline. */
public boolean matches(String candidateHash) {
return schemaHash.equals(candidateHash);
}
}
@@ -0,0 +1,88 @@
package dev.caskeleton.grpc.codegen;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Instant;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcBufPolicyTest {
private static final GrpcSchemaBaseline BASELINE =
new GrpcSchemaBaseline(
"1.4.0",
"sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0",
Instant.parse("2026-08-01T00:00:00Z"));
@Test
@DisplayName("the Stable public API is gated on the FILE breaking category")
void stablePublicApiUsesTheFileCategory() {
GrpcBufPolicy policy = GrpcBufPolicy.stable(BASELINE);
assertThat(policy.breakingCategory()).isEqualTo(GrpcBreakingCategory.FILE);
assertThat(GrpcBreakingCategory.stableGate()).isEqualTo(GrpcBreakingCategory.FILE);
assertThat(policy.breakingCategory().detectsSourceBreak()).isTrue();
assertThat(policy.breakingCategory().detectsFileMove()).isTrue();
}
@Test
@DisplayName("wire-only compatibility may not gate the Stable public API")
void wireOnlyCompatibilityIsRefused() {
assertThatThrownBy(() -> new GrpcBufPolicy(GrpcBreakingCategory.WIRE, true, true, BASELINE))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("stops compiling");
assertThatThrownBy(
() -> new GrpcBufPolicy(GrpcBreakingCategory.WIRE_JSON, true, true, BASELINE))
.isInstanceOf(IllegalArgumentException.class);
assertThat(GrpcBreakingCategory.WIRE.detectsSourceBreak()).isFalse();
assertThat(GrpcBreakingCategory.PACKAGE.detectsFileMove()).isFalse();
}
@Test
@DisplayName("format and lint are not optional")
void formatAndLintAreNotOptional() {
assertThatThrownBy(() -> new GrpcBufPolicy(GrpcBreakingCategory.FILE, false, true, BASELINE))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new GrpcBufPolicy(GrpcBreakingCategory.FILE, true, false, BASELINE))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("the four lifecycle stages are named, and a missing one is reported")
void lifecycleStagesAreNamedAndChecked() {
assertThat(GrpcBufPolicy.requiredTasks())
.containsExactly("bufFormatCheck", "bufLint", "bufBuild", "bufBreaking");
assertThat(GrpcBufPolicy.missingTasks(Set.of("bufFormatCheck", "bufLint", "bufBuild")))
.containsExactly("bufBreaking");
assertThat(GrpcBufPolicy.missingTasks(Set.copyOf(GrpcBufPolicy.requiredTasks()))).isEmpty();
}
@Test
@DisplayName("the breaking baseline is a released version, never a snapshot")
void baselineIsAnImmutableRelease() {
assertThatThrownBy(
() ->
new GrpcSchemaBaseline(
"1.5.0-SNAPSHOT",
"sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0",
Instant.parse("2026-08-01T00:00:00Z")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("immutable release");
assertThatThrownBy(
() ->
new GrpcSchemaBaseline(
"1.5.0", "not-a-digest", Instant.parse("2026-08-01T00:00:00Z")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("an unchanged schema hash needs no breaking review")
void unchangedSchemaNeedsNoBreakingReview() {
GrpcBufPolicy policy = GrpcBufPolicy.stable(BASELINE);
assertThat(policy.unchangedFromBaseline(BASELINE.schemaHash())).isTrue();
assertThat(policy.unchangedFromBaseline("sha256:ffffffffffffffffffffffffffffffff")).isFalse();
}
}
@@ -0,0 +1,78 @@
package dev.caskeleton.grpc.codegen;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcCodegenManifestTest {
@Test
@DisplayName("Java code generation has exactly one owner, and a second is refused")
void codeGenerationHasOneOwner() {
GrpcCodegenManifest manifest = GrpcCodegenManifest.caSkeleton();
manifest.requireSoleOwner("gradle-protobuf-plugin");
assertThatThrownBy(() -> manifest.requireSoleOwner("hand-rolled-protoc-exec"))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("hand-rolled-protoc-exec");
}
@Test
@DisplayName("generator versions come from the managed platform, never from a literal")
void generatorVersionsComeFromTheManagedPlatform() {
assertThatThrownBy(
() ->
new GrpcCodegenManifest(
"gradle-protobuf-plugin",
"3.25.5",
GrpcCodegenManifest.MANAGED_VERSION_SOURCE,
GrpcCodegenOutput.standard(),
new GrpcGeneratedPackagePolicy(
Set.of("dev.caskeleton"), Set.of("hyeonworks.grpc.common.v1.generated"))))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("protobuf version must come from the managed platform");
}
@Test
@DisplayName("generated sources land under build/, never in a source tree")
void generatedSourcesLandUnderBuild() {
assertThatThrownBy(
() -> new GrpcCodegenOutput("src/main/java", "build/g", "build/x.desc", true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("must be under 'build/'");
assertThatThrownBy(() -> new GrpcCodegenOutput("build/a", "build/b", "build/schema.txt", true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("FileDescriptorSet");
assertThat(GrpcCodegenOutput.standard().includeSourceInfo()).isTrue();
}
@Test
@DisplayName("a generated package inside a hand-written one fails the manifest")
void generatedAndHandWrittenPackagesMustBeDisjoint() {
GrpcGeneratedPackagePolicy overlapping =
new GrpcGeneratedPackagePolicy(
Set.of("dev.caskeleton"), Set.of("dev.caskeleton.grpc.generated"));
assertThat(overlapping.overlaps()).hasSize(1);
assertThatThrownBy(overlapping::requireDisjoint)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("dev.caskeleton.grpc.generated");
assertThat(
new GrpcGeneratedPackagePolicy(
Set.of("dev.caskeleton"), Set.of("hyeonworks.grpc.common.v1.generated"))
.overlaps())
.isEmpty();
}
@Test
@DisplayName("an overlap is caught in both directions")
void overlapIsSymmetric() {
GrpcGeneratedPackagePolicy generatedIsAnAncestor =
new GrpcGeneratedPackagePolicy(Set.of("hyeonworks.grpc.hand"), Set.of("hyeonworks.grpc"));
assertThat(generatedIsAnAncestor.overlaps()).hasSize(1);
}
}
@@ -0,0 +1,248 @@
package dev.caskeleton.grpc.codegen;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class GrpcDescriptorArtifactTest {
private static final String DIGEST_A =
"sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0";
private static final String DIGEST_B =
"sha256:1122334455667788990011223344556677889900112233445566778899001122";
private static final GrpcSchemaBaseline BASELINE =
new GrpcSchemaBaseline("1.4.0", DIGEST_A, Instant.parse("2026-08-01T00:00:00Z"));
private static GrpcDescriptorArtifact artifact(
String version, String hash, Set<String> methods, Set<String> javaPackages) {
return new GrpcDescriptorArtifact(
version,
hash,
DIGEST_A,
DIGEST_B,
"grpc-stable-policy-1",
Set.of("hyeonworks.document.v1.DocumentService"),
methods,
javaPackages);
}
private static final Set<String> METHODS =
Set.of(
"hyeonworks.document.v1.DocumentService/GetDocument",
"hyeonworks.document.v1.DocumentService/CreateDocument");
private static final Set<String> PACKAGES = Set.of("hyeonworks.document.v1.generated");
private static String resource(String path) {
try (java.io.InputStream stream =
GrpcDescriptorArtifactTest.class.getClassLoader().getResourceAsStream(path)) {
if (stream == null) {
throw new IllegalStateException("missing test resource " + path);
}
return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
} catch (java.io.IOException e) {
throw new java.io.UncheckedIOException(e);
}
}
@Test
@DisplayName("a schema artifact publishes an immutable version and three digests")
void artifactCarriesAnImmutableVersionAndDigests() {
GrpcDescriptorArtifact candidate = artifact("1.5.0", DIGEST_B, METHODS, PACKAGES);
assertThat(candidate.schemaVersion()).isEqualTo("1.5.0");
assertThat(candidate.unchangedFrom(BASELINE)).isFalse();
assertThat(artifact("1.4.0", DIGEST_A, METHODS, PACKAGES).unchangedFrom(BASELINE)).isTrue();
assertThatThrownBy(() -> artifact("1.5.0-SNAPSHOT", DIGEST_B, METHODS, PACKAGES))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("immutable version");
assertThatThrownBy(() -> artifact("1.5.0", "nope", METHODS, PACKAGES))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("service, method and Java package breaks are reported separately")
void sourceBreaksAreReportedByKind() {
GrpcConsumerFixture consumer =
new GrpcConsumerFixture(
"document-client-v1",
"1.4.0",
Set.of("hyeonworks.document.v1.DocumentService"),
METHODS,
PACKAGES);
GrpcDescriptorArtifact renamedEverything =
new GrpcDescriptorArtifact(
"1.5.0",
DIGEST_B,
DIGEST_A,
DIGEST_B,
"grpc-stable-policy-1",
Set.of("hyeonworks.document.v2.DocumentService"),
Set.of("hyeonworks.document.v2.DocumentService/GetDocument"),
Set.of("hyeonworks.document.v2.generated"));
List<GrpcConsumerFixture.SourceBreak> breaks = consumer.breaksAgainst(renamedEverything);
assertThat(breaks)
.extracting(GrpcConsumerFixture.SourceBreak::kind)
.containsExactlyInAnyOrder(
GrpcConsumerFixture.BreakKind.SERVICE_PATH,
GrpcConsumerFixture.BreakKind.METHOD_PATH,
GrpcConsumerFixture.BreakKind.METHOD_PATH,
GrpcConsumerFixture.BreakKind.JAVA_PACKAGE);
}
@Test
@DisplayName("a consumer that still compiles reports no break")
void compatibleSchemaBreaksNothing() {
GrpcConsumerFixture consumer =
new GrpcConsumerFixture(
"document-client-v1",
"1.4.0",
Set.of("hyeonworks.document.v1.DocumentService"),
METHODS,
PACKAGES);
Set<String> widened =
Set.of(
"hyeonworks.document.v1.DocumentService/GetDocument",
"hyeonworks.document.v1.DocumentService/CreateDocument",
"hyeonworks.document.v1.DocumentService/ArchiveDocument");
assertThat(consumer.breaksAgainst(artifact("1.5.0", DIGEST_B, widened, PACKAGES))).isEmpty();
}
@Test
@DisplayName("the committed v1 consumer fixture states its own requirements")
void theCommittedFixtureStatesItsOwnRequirements() {
GrpcConsumerFixture derived =
GrpcConsumerFixture.fromJavaSource(
"document-client-v1",
"1.4.0",
resource("consumer-fixtures/v1/src/main/java/fixture/DocumentClientFixture.java"),
"generated");
assertThat(derived.requiredServicePaths())
.containsExactly("hyeonworks.document.v1.DocumentService");
assertThat(derived.requiredMethodPaths())
.containsExactlyInAnyOrder(
"hyeonworks.document.v1.DocumentService/GetDocument",
"hyeonworks.document.v1.DocumentService/CreateDocument");
assertThat(derived.requiredJavaPackages()).containsExactly("hyeonworks.document.v1.generated");
}
@Test
@DisplayName("a schema that renames a method the committed fixture calls blocks the release")
void renamingAMethodTheFixtureCallsBlocksTheRelease() {
GrpcConsumerFixture derived =
GrpcConsumerFixture.fromJavaSource(
"document-client-v1",
"1.4.0",
resource("consumer-fixtures/v1/src/main/java/fixture/DocumentClientFixture.java"),
"generated");
GrpcDescriptorArtifact renamed =
new GrpcDescriptorArtifact(
"1.5.0",
DIGEST_B,
DIGEST_A,
DIGEST_B,
"grpc-stable-policy-1",
Set.of("hyeonworks.document.v1.DocumentService"),
Set.of(
"hyeonworks.document.v1.DocumentService/GetDocument",
"hyeonworks.document.v1.DocumentService/CreateDocumentV2"),
Set.of("hyeonworks.document.v1.generated"));
GrpcSchemaArtifactPublisher publisher =
new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE));
assertThat(publisher.evaluate(renamed, List.of(derived)).blockers())
.anySatisfy(blocker -> assertThat(blocker).contains("CreateDocument"));
}
@Test
@DisplayName("a fixture that requires nothing is refused rather than passing every schema")
void aFixtureThatRequiresNothingIsRefused() {
assertThatThrownBy(
() ->
GrpcConsumerFixture.fromJavaSource(
"empty-client", "1.4.0", "package fixture;\n\nclass Empty {}\n", "generated"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cannot detect a break");
}
@Test
@DisplayName("the fixture's own build file pins the schema version it was built against")
void theFixturePinsItsSchemaVersion() {
assertThat(resource("consumer-fixtures/v1/build.gradle.kts"))
.contains("grpc-schema-artifact:1.4.0")
.contains("floats to the latest version");
}
@Test
@DisplayName("a consumer fixture failure blocks the release")
void consumerFixtureFailureBlocksTheRelease() {
GrpcSchemaArtifactPublisher publisher =
new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE));
GrpcConsumerFixture consumer =
new GrpcConsumerFixture(
"document-client-v1",
"1.4.0",
Set.of("hyeonworks.document.v1.DocumentService"),
METHODS,
PACKAGES);
GrpcDescriptorArtifact dropsAMethod =
artifact(
"1.5.0",
DIGEST_B,
Set.of("hyeonworks.document.v1.DocumentService/GetDocument"),
PACKAGES);
GrpcSchemaArtifactPublisher.PublishDecision decision =
publisher.evaluate(dropsAMethod, List.of(consumer));
assertThat(decision.allowed()).isFalse();
assertThat(decision.blockers())
.anySatisfy(
blocker ->
assertThat(blocker).contains("document-client-v1").contains("CreateDocument"));
assertThatThrownBy(() -> publisher.publish(dropsAMethod, decision))
.isInstanceOf(IllegalStateException.class);
}
@Test
@DisplayName("a released version may not be republished with different bytes")
void releasedVersionsAreImmutable() {
GrpcSchemaArtifactPublisher publisher =
new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE));
GrpcDescriptorArtifact first = artifact("1.5.0", DIGEST_B, METHODS, PACKAGES);
GrpcSchemaArtifactPublisher.PublishDecision allowed = publisher.evaluate(first, List.of());
assertThat(allowed.allowed()).isTrue();
publisher.publish(first, allowed);
assertThat(publisher.publishedHash("1.5.0")).isEqualTo(DIGEST_B);
GrpcDescriptorArtifact sameVersionDifferentBytes =
artifact("1.5.0", DIGEST_A, METHODS, PACKAGES);
assertThat(publisher.evaluate(sameVersionDifferentBytes, List.of()).blockers())
.anySatisfy(blocker -> assertThat(blocker).contains("immutable"));
}
@Test
@DisplayName("republishing identical bytes under the same version is allowed")
void identicalRepublishIsAllowed() {
GrpcSchemaArtifactPublisher publisher =
new GrpcSchemaArtifactPublisher(GrpcBufPolicy.stable(BASELINE));
GrpcDescriptorArtifact artifact = artifact("1.5.0", DIGEST_B, METHODS, PACKAGES);
publisher.publish(artifact, publisher.evaluate(artifact, List.of()));
assertThat(publisher.evaluate(artifact, List.of()).allowed()).isTrue();
assertThat(publisher.policy().breakingCategory()).isEqualTo(GrpcBreakingCategory.FILE);
}
}
@@ -0,0 +1,17 @@
// The v1 consumer fixture's own build file, kept as a test resource.
//
// It is not part of this repository's Gradle build. Its purpose is to record what a released
// consumer actually depended on — the schema artifact version and nothing else — so that when
// protoc generation is switched on (ADR-GRPC-002) this directory can be compiled as-is against a
// candidate schema, which is the check GrpcConsumerFixture currently approximates from source text.
plugins {
`java-library`
}
dependencies {
// The released schema artifact, pinned. A fixture that floats to the latest version cannot
// detect a break, because it is always built against the schema it is meant to be testing.
implementation("dev.caskeleton.grpc:grpc-schema-artifact:1.4.0")
implementation("io.grpc:grpc-stub")
implementation("io.grpc:grpc-protobuf")
}
@@ -0,0 +1,33 @@
package fixture;
import hyeonworks.document.v1.generated.CreateDocumentRequest;
import hyeonworks.document.v1.generated.DocumentServiceGrpc;
import hyeonworks.document.v1.generated.GetDocumentRequest;
/**
* A previously released consumer, kept as a fixture rather than as a dependency.
*
* <p>This file is a test resource, not a compiled source. It records exactly what the v1 client
* named — the generated package it imported from, the service class it referenced and the methods it
* called — so a candidate schema can be checked against a real client's surface instead of against a
* requirement list somebody typed by hand and will forget to update.
*
* <p>{@code GrpcConsumerFixture.fromJavaSource} derives those three sets from this text. Adding a
* call here widens what a release must keep; that is the intent.
*/
public final class DocumentClientFixture {
private final DocumentServiceGrpc.DocumentServiceBlockingStub stub;
public DocumentClientFixture(DocumentServiceGrpc.DocumentServiceBlockingStub stub) {
this.stub = stub;
}
public String read(String documentId) {
return stub.getDocument(GetDocumentRequest.newBuilder().setId(documentId).build()).getTitle();
}
public String create(String title) {
return stub.createDocument(CreateDocumentRequest.newBuilder().setTitle(title).build()).getId();
}
}