We are going to create a CI pipeline that checks for breaking changes in GraphQL and Protobuf schemas.
We assume that the project has two types of schemas: GraphQL (SDL) and Protobuf (proto files).
We want to run a diff between the current schema (in the PR) and the base schema (usually the main branch) and fail if there are breaking changes.
Steps:
- Check out the code.
- Set up the environment (install tools for GraphQL and Protobuf).
- For each schema type (GraphQL and Protobuf), we will:
a. Extract the current schema from the PR and the base schema from the base branch.
b. Run a compatibility check (using appropriate tools) between the two.
c. Fail the CI if breaking changes are detected.
We assume that the schemas are stored in a known directory (e.g., schemas/ for GraphQL and proto/ for Protobuf).
However, the exact location can be configured.
Tools:
For GraphQL: We can use graphql package and graphql-schema-linters or apollo-federation if using federation, but a common tool is graphql's buildSchema and then compare.
However, for a more robust solution, we can use @graphql-tools/schema and @graphql-tools/relay for compatibility?
Actually, there is a tool called graphql-schema-diff or graphql-compatibility but let's see.
Alternatively, we can use graphql's buildSchema and then use graphql's assertValidSchema and then try to see if the old schema is a subset of the new one?
But note: We want to detect breaking changes (i.e., changes that would break existing clients).
A common approach for GraphQL is to use graphql's buildSchema and then use graphql's validate function to validate the new schema against the old one?
Actually, we want to check if the new schema is backward compatible with the old one. This is non-trivial.
We can use the concept of schema diffing from Apollo: https://www.apollographql.com/docs/devtools/schema-change-alerts/
They have a tool called apollo that can do this, but it requires an Apollo account.
Alternatively, we can use @graphql-tools/schema and @graphql-tools/relay to transform the schema and then compare?
However, there is a package graphql-schema-diff that might help, but it's not very active.
Another option: graphql-compatibility (https://github.com/ evenlydivided/graphql-compatibility) but it's not maintained.
Given the complexity, we might have to write our own or use a combination of tools.
But note: We are in CI and want a simple solution.
Let me propose:
For GraphQL:
- We will use
graphql (the reference implementation) to parse both schemas (SDL) into GraphQLSchema objects.
- Then we will check for breaking changes by ensuring that:
- All types, fields, and arguments that existed in the old schema still exist in the new one (with compatible types).
- No required fields have been removed.
- No enum values have been removed.
- etc.
However, this is complex. Alternatively, we can use the graphql package's buildSchema and then use assertValidSchema to ensure the new schema is valid, but that doesn't check compatibility.
There is a known algorithm for checking GraphQL schema compatibility:
- For each operation in the old schema (queries, mutations, subscriptions) we validate against the new schema? But we don't have the operations.
Since we don't have the operations, we have to check the schema itself. We can use the following rules (from Apollo's breaking change detection):
- Removing a field or type.
- Making a field non-nullable that was nullable.
- Changing the type of a field (except to a nullable version? Actually, changing to a more general type might be safe?).
- Removing an enum value.
But note: Adding fields or types is safe.
We can write a script that does this, but it's a lot of work.
Alternatively, we can use graphql-schema-linter with some rules? It has rules for deprecations but not for breaking changes.
Given the time, maybe we can use an existing tool. Let me search:
Since we are in CI and might not want to use Apollo, we can use graphql-schema-diff but it's outdated.
Another option: @graphql-inspector (https://github.com/kamilkisiela/graphql-inspector) - it is a set of tools for schema diff and validation.
We can use @graphql-inspector/cli in CI. It supports:
- Detecting breaking changes, safe changes, and diff.
- It can compare two schemas (SDL or introspection) and output breaking changes.
So, for GraphQL, we can:
Step 1: Generate introspection for the old and new schemas (if we have SDL, we can use graphql to build the schema and then get introspection).
Step 2: Run graphql-inspector diff between the two.
However, note: @graphql-inspector requires Node.js and might be heavy, but it's maintained.
Alternatively, we can use the graphql-inspector Docker image? But we can also install via npm.
Let's do:
npm install -g @graphql-inspector/cli
Then:
Generate introspection for old schema
graphql-inspector introspect old-schema.graphql > old-schema.json
Generate introspection for new schema
graphql-inspector introspect new-schema.graphql > new-schema.json
Compare
graphql-inspector diff old-schema.json new-schema.json --format json
But note: we are in CI and we want to fail on breaking changes.
graphql-inspector diff old-schema.json new-schema.json --require-approval false
This will exit with non-zero if there are breaking changes? Actually, by default, it prints the changes and exits with 0? Let's check.
According to the docs:
--require-approval (default: true) - if set to false, the command will exit with an error code when there are breaking changes.
So we can do:
graphql-inspector diff old.json new.json --require-approval false
But note: we are in a PR, so we have to get the old and new schemas. We can get the old schema from the base branch and the new from the current branch.
How to get the files? We assume the schema files are in a fixed location. We can:
- For the old schema: checkout the base branch and copy the schema file to a temp location.
- For the new schema: use the current branch's schema file.
However, note that the schema might be split into multiple files? GraphQL can be in multiple files (usingSDL). We have to concatenate them? Or use a tool that can handle multiple files.
graphql-inspector can take a directory? Actually, it can take a file or a directory? The introspect command can take a directory and it will merge? Not sure.
Alternatively, we can use graphql-tools to stitch multiple SDL files? But that's complex.
Since we are in CI, we can assume the schema is in one file? Or we can have a build step that generates a single SDL from multiple files?
Let's assume for simplicity we have a single SDL file for GraphQL. If not, we have to adjust.
For Protobuf:
We can use protoc and then use protoc-gen-validate? Or use buf which has breaking change detection.
Actually, buf (https://buf.build/) has a buf breaking command that checks for breaking changes between two versions of protobuf schemas.
Steps for Protobuf:
1. Install `buf` (https://buf.build/docs/installation) or use a Docker image.
2. We need to have the old and new protobuf files. We assume they are in a directory (e.g., `proto/`).
3. We can use `buf breaking` against a base (the old schema) and the current (new schema).
But note: buf requires a buf.yaml configuration? It can work without? Actually, it can work with just the files.
Example:
buf breaking --against .git#branch=main
This will compare the current protobuf files (in the current branch) against the ones in the main branch.
However, we are in CI and we have the base branch (the target branch of the PR). We can set up:
buf breaking --against $BASE_BRANCH
But note: buf breaking by default uses the current directory and the --against can be a git reference.
We can do:
# In the current branch, we have the new protobuf files.
# We want to compare against the base branch (the one we are merging into).
buf breaking --against .git#branch=$BASE_BRANCH
However, we must have the base branch's code checked out? Actually, buf with --against .git#branch=main will fetch from git?
According to the docs:
--against can be a git reference, but it must be a local git reference? So we need to fetch the base branch.
In CI, we usually have the base branch available? In GitHub Actions, we have the event that triggered the PR, so we can get the base branch.
Alternatively, we can:
git fetch origin $BASE_BRANCH
buf breaking --against .git#branch=origin/$BASE_BRANCH
But note: buf might require the files to be in a specific module? We can also use buf breaking --config buf.yaml if we have a config.
Since we are in a monorepo, we might have multiple modules? We assume the protobuf files are in one module.
Alternatively, we can use protoc and the protoc-gen-validate plugin? But that's for validation, not breaking changes.
So, buf is the way to go.
However, note: buf might not be installed. We can install it via npm? Actually, buf is a Go tool, but they provide a npm package?
There is a @bufbuild/buf npm package? But it's for the buf client in Node.js? Actually, the CLI is written in Go and they provide binaries.
We can download the binary from GitHub releases.
Alternatively, we can use a Docker image: bufbuild/buf.
Let's use the Docker image for simplicity in CI.
Steps for Protobuf with buf:
docker run --rm -v $(pwd):/workspace -w /workspace bufbuild/buf:latest breaking --against .git#branch=$BASE_BRANCH
But note: we need to have the base branch's code. We can do:
git fetch origin $BASE_BRANCH
docker run ... breaking --against .git#branch=origin/$BASE_BRANCH
However, the buf image might not have git? We can run git fetch in the host and then mount the entire .git?
Alternatively, we can check out the base branch in a separate directory and then use --against pointing to that directory?
The --against flag can also take a directory:
buf breaking --against /path/to/base/proto
So we can:
- Checkout the base branch in a temporary directory? Or we can have the base branch's code in the same repo?
In CI, we usually have the code of the current branch and the base branch is available via git? We can do:
git worktree add /tmp/base $BASE_BRANCH
Then:
buf breaking --against /tmp/base/proto
But note: the current branch's protobuf files are in the current directory (or a subdirectory). So we can run buf breaking in the current directory and point --against to the base branch's directory.
However, buf expects the module to be defined? We might need a buf.yaml in the protobuf directory.
So, let's assume we have a buf.yaml in the root of the protobuf directory (or we can set --config).
If we don't have a buf.yaml, we can create one? Or we can use --path to specify the directory.
Alternatively, we can run buf breaking in the protobuf directory and use --against the base branch's protobuf directory.
Steps:
# In the current branch, we are in the repo root. We assume the protobuf files are in `proto/`.
# We have fetched the base branch and added a worktree at `/tmp/base` (which is the base branch's code).
cd proto
buf breaking --against /tmp/base/proto
But note: the base branch might have a different structure? We assume the same.
Alternatively, we can avoid worktree and just copy the base branch's proto files? But that might be heavy.
Given the complexity, we might just use the git reference method and hope that buf can access the git repository?
Actually, buf breaking --against .git#branch=main requires that the current directory is a git repository and that the branch is available (fetched).
So we can:
git fetch origin $BASE_BRANCH
cd proto
buf breaking --against .git#branch=origin/$BASE_BRANCH
This should work if we are in the same git repository and the branch is fetched.
But note: the buf Docker image must have git installed? The bufbuild/buf image does have git? Let's check:
The Dockerfile for bufbuild/buf is based on alpine and they install git? I think they do.
Alternatively, we can run without Docker and install buf on the CI runner.
Since we are using GitHub Actions, we can use setup-buf action? There is an action: bufbuild/buf-action but it's for setting up buf.
Let's do:
- uses: bufbuild/buf-action@v1
with:
token: ${{ secrets.BUF_TOKEN }} # if we use Buf Studio, but we don't need for local breaking?
# Actually, for breaking, we don't need a token.
But note: the buf-action sets up buf in the PATH.
Then we can run buf breaking without Docker.
However, we might not want to use an action. We can install via script.
Given the time, let's use the Docker approach for consistency.
But note: the buf version in Docker might be old? We can specify a tag.
Alternatively, we can use the buf npm package? There is a @bufbuild/buf package that provides the CLI? Actually, no, they provide a client library.
So, let's stick to Docker or installing the binary.
Since we are in CI and want to avoid installing, Docker is easier.
However, if the CI runner doesn't have Docker, we have to install the binary.
Let's assume we are using GitHub Actions and we can use Docker.
Steps for Protobuf:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0 # we need the history to fetch the base branch
- name: Fetch base branch
run: git fetch origin ${{ github.base_ref }}
- name: Run buf breaking
run: |
cd proto
docker run --rm -v $(pwd):/workspace -w /workspace bufbuild/buf:latest breaking --against .git#branch=origin/${{ github.base_ref }}
But note: the current directory for buf must be the one with the buf.yaml? Or we can specify --config?
We assume the buf.yaml is in the proto/ directory.
If not, we can adjust the --config flag.
Also, note: the buf command might output breaking changes and exit with non-zero if there are breaking changes.
According to the docs:
buf breaking exits with 0 if there are no breaking changes, and non-zero otherwise.
So we can rely on that.
However, we want to see the breaking changes in the CI logs? buf breaking will output them.
Now, for GraphQL:
We will use graphql-inspector in a similar way.
Steps for GraphQL:
- We assume we have a single SDL file (or we can stitch multiple). We'll assume a single file for now.
- We need to get the old schema from the base branch and the new from the current branch.
- We can do:
# Checkout the base branch and copy the schema file to a temp location?
git fetch origin ${{ github.base_ref }}
git show origin/${{ github.base_ref }}:path/to/schema.graphql > old-schema.graphql
# Then use the current branch's schema.graphql (which is in the working directory) as the new one.
# Then run graphql-inspector diff.
But note: the schema might be in a different location in the base branch? We assume the same path.
Alternatively, we can use git show to get the old schema and compare with the current file.
We can write a script:
old_schema=$(git show origin/${{ github.base_ref }}:schemas/schema.graphql)
new_schema=$(cat schemas/schema.graphql)
Then write them to files and run `graphql-inspector diff`.
But graphql-inspector expects two files? Yes.
However, if we have multiple files, we have to combine them? We can use cat to combine multiple SDL files? But note: GraphQL SDL can have imports?
We assume no imports, or we have a build step that produces a single SDL.
Alternatively, we can use graphql-inspector with two directories? I don't think so.
So, we assume a single SDL file.
Steps:
- name: Install graphql-inspector
run: npm install -g @graphql-inspector/cli
- name: Get old schema
run: git show origin/${{ github.base_ref }}:schemas/schema.graphql > old-schema.graphql
- name: Get new schema (already in the repo, but we might have changed it)
run: cp schemas/schema.graphql new-schema.graphql
- name: Run graphql-inspector diff
run: graphql-inspector diff old-schema.graphql new-schema.graphql --require-approval false
But note: the --require-approval false will cause the command to exit with non-zero if there are breaking changes.
However, what about safe changes? We don't care about safe changes? We only want to fail on breaking.
Also, note: graphql-inspector by default compares the entire schema? Yes.
But what if we have multiple operations? We don't have operations, so we are only checking the schema.
This should be okay.
However, note: graphql-inspector might have false positives? We have to test.
Alternatively, we can use apollo CLI if we have an Apollo account and the schemas are in Apollo Studio? But that's a different setup.
Given the constraints, we'll use graphql-inspector.
But note: graphql-inspector might not be maintained? It is maintained by the same author of graphql-inspector (Kamil Kisiela) and it's used by many.
However, it requires Node.js and might be slow for large schemas.
We can also consider graphql-schema-compare (https://github.com/paulkim/graphql-schema-compare) but it's not as feature-rich.
Let's stick with graphql-inspector.
Now, we have to combine these two checks in one CI job? Or separate jobs?
We can have one job that does both, or two separate jobs. Since they are independent, we can do two jobs.
But note: if one fails, we want to fail the CI. So we can have one job that runs both and fails if any fails.
Alternatively, we can have two jobs and then a third that depends on both? But that's overkill.
Let's do one job that runs both checks.
Steps:
- Checkout code (with fetch-depth 0 to get the base branch)
- Fetch the base branch
- Run GraphQL check
- Run Protobuf check
But note: the base branch might be different for GraphQL and Protobuf? Usually, they are in the same repo and we compare against the same base.
However, what if the schemas are in different directories? We have to adjust.
We assume:
GraphQL schema: `schemas/schema.graphql`
Protobuf schema: `proto/` (directory)
We can make these configurable via environment variables.
Let's create a script that:
1. Sets variables for the paths.
2. Does the GraphQL check.
3. Does the Protobuf check.
But note: the GraphQL check might fail if the file doesn't exist? We can skip if the file doesn't exist? Or we can have a flag.
We assume the project has both. If not, we can conditionally run.
We can do:
if [ -f "$GRAPHQL_SCHEMA_PATH" ]; then
... run graphql-inspector
fi
Similarly for Protobuf.
Let's write a shell script for the CI:
We'll create a file ci/check-schemas.sh:
#!/bin/bash
set -e # exit on error
GRAPHQL_SCHEMA_PATH=${GRAPHQL_SCHEMA_PATH:-"schemas/schema.graphql"}
PROTOBUF_DIR=${PROTOBUF_DIR:-"proto"}
BASE_BRANCH=${BASE_BRANCH:-$1}
if [ -z "$BASE_BRANCH" ]; then
echo "BASE_BRANCH is not set. Please set the BASE_BRANCH environment variable or pass as the first argument."
exit 1
fi
echo "Fetching base branch: $BASE_BRANCH"
git fetch origin $BASE_BRANCH
# GraphQL check
if [ -f "$GRAPHQL_SCHEMA_PATH" ]; then
echo "Running GraphQL schema compatibility check..."
# Install graphql-inspector
npm install -g @graphql-inspector/cli
# Get old and new schemas
git show origin/$BASE_BRANCH:$GRAPHQL_SCHEMA_PATH > old-schema.graphql
cp $GRAPHQL_SCHEMA_PATH new-schema.graphql
# Run diff
graphql-inspector diff old-schema.graphql new-schema.graphql --require-approval false
else
echo "GraphQL schema not found at $GRAPHQL_SCHEMA_PATH. Skipping."
fi
# Protobuf check
if [ -d "$PROTOBUF_DIR" ]; then
echo "Running Protobuf schema compatibility check..."
cd $PROTOBUF_DIR
# Check if there is a buf.yaml? If not, we can try without? buf breaking requires a module?
# We assume there is a buf.yaml or we are in a module.
# Run buf breaking with Docker
docker run --rm -v $(pwd):/workspace -w /workspace bufbuild/buf:latest breaking --against .git#branch=origin/$BASE_BRANCH
else
echo "Protobuf directory not found at $PROTOBUF_DIR. Skipping."
fi
Then in our CI configuration (e.g., GitHub Actions):
jobs:
schema-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Check schemas
run: |
bash ci/check-schemas.sh ${{ github.base_ref }}
env:
GRAPHQL_SCHEMA_PATH: "schemas/schema.graphql"
PROTOBUF_DIR: "proto"
However, note: the docker run command might fail if the protobuf directory is not at the root? We are changing to the protobuf directory and then mounting the current directory (which is now the protobuf directory) to /workspace. Then we run buf breaking in /workspace, and the --against .git#branch=origin/$BASE_BRANCH will look for the base branch's protobuf files in the same relative path?
Actually, the --against uses the git reference and then the same path as the current module? It might not find the base branch's files if they are in a different location?
We assume the protobuf files are in the same relative path in the base branch.
Alternatively, we can use --against with a directory? We can do:
We have the base branch's code in the same repository? We can use:
buf breaking --against ../path/to/base/proto
But we don't have the base branch's code in a separate directory? We have it in the same git repo, but we are in a worktree?
Actually, we are not checking out the base branch in a separate directory. We are using the git reference.
So, the buf breaking command will use the current directory (the protobuf directory in the current branch) and then for the base branch, it will look at the same relative path in the base branch?
That should work if the protobuf files are in the same location in both branches.
But note: what if the protobuf directory moved? Then it might fail? We assume it didn't move.
Alternatively, we can check out the base branch in a temporary directory and then use --against with that directory.
Let's change the Protobuf part:
# Create a temporary directory for the base branch's protobuf files
BASE_PROTO_DIR=$(mktemp -d)
# Checkout the base branch's protobuf directory (only the protobuf files) to the temp dir?
# We can use `git checkout` but we are in a script and we don't want to disturb the current working directory.
# Instead, we can use `git show` to get the entire directory? That's complex.
# Alternatively, we can do:
git archive origin/$BASE_BRANCH $PROTOBUF_DIR | tar -x -C $BASE_PROTO_DIR
Then:
buf breaking --against $BASE_PROTO_DIR
But note: buf breaking expects a directory that has a buf.yaml? Or it will look for one in the parent directories?
We are in the current branch's protobuf directory, and we have a buf.yaml there? We assume so.
For the base, we are extracting the same directory structure (the protobuf files) to $BASE_PROTO_DIR. Then we run buf breaking in the current protobuf directory and point --against to $BASE_PROTO_DIR.
Steps:
cd $PROTOBUF_DIR
BASE_PROTO_DIR=$(mktemp -d)
git archive origin/$BASE_BRANCH $PROTOBUF_DIR | tar -x -C $BASE_PROTO_DIR
# Now, the base protobuf files are in $BASE_PROTO_DIR (which is a directory that has the same structure as $PROTOBUF_DIR? Actually, we extracted the entire $PROTOBUF_DIR from the base branch to $BASE_PROTO_DIR, so we have:
$BASE_PROTO_DIR/
... the files that were in $PROTOBUF_DIR in the base branch.
Then we run:
buf breaking --against $BASE_PROTO_DIR
But note: the current directory is PROTOBUFDIRandthebaseisBASE_PROTO_DIR. They have the same structure? Yes, because we extracted the same directory.
However, what if the base branch's protobuf directory has a different name? We are using the same $PROTOBUF_DIR variable for the base branch?
Actually, we are archiving the $PROTOBUF_DIR from the base branch and extracting to $BASE_PROTO_DIR. So the base branch's protobuf directory (which might be named differently) is now at $BASE_PROTO_DIR?
Wait: git archive origin/$BASE_BRANCH $PROTOBUF_DIR will archive the directory $PROTOBUF_DIR (relative to the root) from the base branch. Then we extract to $BASE_PROTO_DIR. So the contents of $PROTOBUF_DIR in the base branch are now in $BASE_PROTO_DIR (without the parent directory).
Example:
In the base branch, we have:
proto/file1.proto
proto/file2.proto
We run:
git archive origin/main proto | tar -x -C /tmp/base_proto
Then we have:
/tmp/base_proto/file1.proto
/tmp/base_proto/file2.proto
And in the current branch, we are in the `proto` directory and we have the same structure.
Then we run `buf breaking --against /tmp/base_proto` from the current `proto` directory?
But note: `buf breaking` expects the `--against` directory to have the same module structure? Actually, it will compare the current directory (which is the module) with the `--against` directory (which should be the same module from the base branch).
So it should work.
However, what if the base branch's protobuf directory is named differently? Then we are archiving a different directory?
We are using the same $PROTOBUF_DIR variable for the base branch? That assumes that in the base branch, the protobuf directory is at the same path?
But we are comparing the current branch's protobuf directory (at $PROTOBUF_DIR) with the base branch's protobuf directory at the same path?
What if the base branch moved the protobuf directory? Then we are archiving the old path?
Actually, we are archiving the path $PROTOBUF_DIR (which is the current branch's path) from the base branch. If in the base branch, the protobuf directory was at a different path, then we are archiving the wrong directory?
So we must know the path of the protobuf directory in the base branch? We assume it's the same.
Alternatively, we can have two variables:
CURRENT_PROTOBUF_DIR and BASE_PROTOBUF_DIR.
But for simplicity, we assume the same.
Given the complexity, maybe we should stick to the git reference method and hope that buf can handle the path change?
Actually, the --against .git#branch=origin/$BASE_BRANCH will look at the same path as the current module?
Let's read the buf docs:
--against can be a git reference, and it will use the same path as the current module?
I think it does. Because it's comparing the current module (which is defined by the buf.yaml in the current directory) with the same module in the base branch?
So if the module path changed, then it might not find the same module?
We assume the module didn't move.
Given the time, let's stick to the simpler --against .git#branch=origin/$BASE_BRANCH and hope the protobuf directory didn't move.
We'll change the script to:
# In the protobuf directory (current branch)
buf breaking --against .git#branch=origin/$BASE_BRANCH
And we assume that the protobuf directory (the module) is at the same relative path in the base branch.
Now, let's write the final script.
However, note: the graphql-inspector might require the schemas to be in a specific format? We are using SDL? It supports SDL.
Also, note: graphql-inspector might have performance issues with large schemas? We can try.
We'll write the script and then the GitHub Action.
But note: the graphql-inspector might not be installed globally? We do npm install -g which might fail if we don't have npm? We are on ubuntu-latest, we have node and npm.
Alternatively, we can use npx to avoid global install? But npx might not be available? It is available with npm.
Let's use npx:
npx @graphql-inspector/cli diff old-schema.graphql new-schema.graphql --require-approval false
But then we don't need to install globally.
So:
- name: Run graphql-inspector diff
run: npx @graphql-inspector/cli diff old-schema.graphql new-schema.graphql --require-approval false
This will use the latest version? Or we can specify a version? We can let it use the latest.
Now, let's write the GitHub Action:
name: Schema Compatibility Check
on:
pull_request:
branches: [ main ]
jobs:
schema-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Check schemas
run: |
#!/bin/bash
set -e
GRAPHQL_SCHEMA_PATH=${GRAPHQL_SCHEMA_PATH:-"schemas/schema.graphql"}
PROTOBUF_DIR=${PROTOBUF_DIR:-"proto"}
BASE_BRANCH=${BASE_BRANCH:-$1}
if [ -z "$BASE_BRANCH" ]; then
echo "BASE_BRANCH is not set. Please set the BASE_BRANCH environment variable or pass as the first argument."
exit 1
fi
echo "Fetching base branch: $BASE_BRANCH"
git fetch origin $BASE_BRANCH
# GraphQL check
if [ -f "$GRAPHQL_SCHEMA_PATH" ]; then
echo "Running GraphQL schema compatibility check..."
git show origin/$BASE_BRANCH:$GRAPHQL_SCHEMA_PATH > old-schema.graphql
cp $GRAPHQL_SCHEMA_PATH new-schema.graphql
npx @graphql-inspector/cli diff old-schema.graphql new-schema.graphql --require-approval false
else
echo "GraphQL schema not found at $GRAPHQL_SCHEMA_PATH. Skipping."
fi
# Protobuf check
if [ -d "$PROTOBUF_DIR" ]; then
echo "Running Protobuf schema compatibility check..."
cd $PROTOBUF_DIR
# Check if buf.yaml exists? If not, we might skip? Or we can create a minimal one?
if [ ! -f "buf.yaml" ]; then
echo "buf.yaml not found in $PROTOBUF_DIR. Skipping Protobuf check."
else
# Run buf breaking with Docker
docker run --rm -v $(pwd):/workspace -w /workspace bufbuild/buf:latest breaking --against .git#branch=origin/$BASE_BRANCH
fi
else
echo "Protobuf directory not found at $PROTOBUF_DIR. Skipping."
fi
shell: bash
env:
GRAPHQL_SCHEMA_PATH: "schemas/schema.graphql"
PROTOBUF_DIR: "proto"
However, note: the docker run might fail if the buf image is not pulled? It will pull automatically? Yes, but it might take time.
Also, note: the graphql-inspector might take time to install via npx? It will download the package.
We can cache the npm packages? But for simplicity, we leave it.
This is a starting point.
Let's test with a simple example.
But note: the graphql-inspector might not work with SDL that has multiple files? We assume one file.
If we have multiple files, we have to combine them into one? We can use cat but note that the order might matter?
We can do:
# For GraphQL, if we have multiple files, we can concatenate them? But note that GraphQL SDL can have imports? We assume no imports.
# Alternatively, we can use `graphql-inspector` with a directory? It doesn't support.
So we have to have a single SDL file. We can have a build step that produces a single SDL from multiple files?
We can adjust the script to:
If the GRAPHQL_SCHEMA_PATH is a directory, then we can combine all .graphql files? But we have to be careful about order?
Alternatively, we can use graphql-tools to stitch? That's too heavy.
Let's assume we have a single file.
If the project has multiple, we can change the CI to use a built single SDL.
Now, for Protobuf, we assume the module is defined in buf.yaml and the files are in the same directory.
This should work for many projects.
However, note: the buf breaking might require the buf.yaml to have a version? Actually, for breaking changes, it doesn't require a version? It just compares the schemas.
We can have a minimal buf.yaml:
version: v1
name: module-name
But we don't need the name? Actually, buf requires a name for the module? Yes, it does.
So we assume the project already has a buf.yaml.
If not, we have to create one? We can skip the Protobuf check if there's no buf.yaml.
We added a check for buf.yaml.
Now, what about the base branch? We are using origin/$BASE_BRANCH. We must have fetched the base branch? Yes, we did git fetch origin $BASE_BRANCH.
But note: the BASE_BRANCH environment variable? We are passing ${{ github.base_ref }} as the argument?
In the GitHub Action, we set:
run: |
bash ci/check-schemas.sh ${{ github.base_ref }}
And in the script, we use $1 as the base branch.
But we also set BASE_BRANCH=${BASE_BRANCH:-$1}. So we can set it via environment or as an argument.
We are passing as an argument.
Now, what about the graphql-inspector? It might not support some GraphQL features? We have to test.
This is a basic setup.
Let's improve:
-
We can cache the npx dependencies? Not critical.
-
We can use a specific version of graphql-inspector? We can change the command to:
npx @graphql-inspector/cli@0.5.0 diff ...
-
Similarly, for buf, we can pin the Docker image tag.
Now, what about the case when there are no changes in the schema? Then the diff should be empty and graphql-inspector and buf should exit with 0.
We are done.
However, note: the graphql-inspector might output a lot of information. We can use --format json and then parse? But we just want to fail on breaking changes.
We are using --require-approval false which will break the build on breaking changes and output the changes.
Similarly, buf breaking will output the breaking changes and exit with non-zero.
So we are good.
Let's write the final script and GitHub Action.
But note: the graphql-inspector might not be able to handle SDL that has custom scalar definitions? It should, because it uses graphql core.
We assume the schemas are valid.
We can also validate the schemas first? But graphql-inspector will validate when it builds the schema? I think so.
Now, what about the case when the schema file is removed? Then git show will fail? We are checking if the file exists in the current branch, but what about the base branch?
If the file was removed in the current branch, then we don't have it, so we skip the GraphQL check? But that might be a breaking change?
Actually, if the schema file is removed, then we are removing the entire schema? That's a breaking change.
We should handle that.
We can change:
For GraphQL:
If the file exists in the base branch but not in the current branch, then that's a breaking change (removing the entire schema).
If the file exists in both, then we compare.
If the file doesn't exist in the base branch but exists in the current branch, that's safe (adding a schema?).
But note: we might have multiple schema files? We are only checking one.
Given the complexity, we assume the schema file exists in both? If not, we can fail.
Let's adjust:
We check if the file exists in the base branch? We can do:
if git show origin/$BASE_BRANCH:$GRAPHQL_SCHEMA_PATH > /dev/null 2>&1; then
# exists in base branch
if [ -f "$GRAPHQL_SCHEMA_PATH" ]; then
# exists in current branch, do diff
else
# removed in current branch -> breaking
echo "GraphQL schema was removed! This is a breaking change."
exit 1
fi
else
# doesn't exist in base branch, so it's new -> safe
echo "GraphQL schema is new. No breaking changes."
fi
Similarly for Protobuf: if the entire directory is removed? Then buf breaking might fail? We can check if the directory exists in the base branch?
We can do:
if git ls-tree -r --name-only origin/$BASE_BRANCH -- $PROTOBUF_DIR | head -1 | grep -q .; then
# there are files in the base branch
if [ -d "$PROTOBUF_DIR" ]; then
# run buf breaking
else
echo "Protobuf directory was removed! This is a breaking change."
exit 1
fi
else
echo "Protobuf directory is new. No breaking changes."
fi
But note: the git ls-tree might be heavy? We can do:
if git show origin/$BASE_BRANCH:$PROTOBUF_DIR > /dev/null 2>&1; then ...
But that checks if the directory exists? Actually, git show on a directory will fail? It will show the tree? I think it will fail.
Alternatively, we can check with git ls-tree:
if git ls-tree -d origin/$BASE_BRANCH $PROTOBUF_DIR > /dev/null 2>&1; then
This checks if the directory exists in the base branch.
Let's adjust the script accordingly.
However, note: the buf breaking command might fail if the directory doesn't exist in the current branch? We are already checking if the directory exists.
So we can do:
For GraphQL:
base_has_schema=$(git show origin/$BASE_BRANCH:$GRAPHQL_SCHEMA_PATH > /dev/null 2>&1 && echo "yes" || echo "no")
current_has_schema=$([ -f "$GRAPHQL_SCHEMA_PATH" ] && echo "yes" || echo "no")
if [ "$base_has_schema" = "yes" ] && [ "$current_has_schema" = "yes" ]; then
# do diff
elif [ "$base_has_schema" = "yes" ] && [ "$current_has_schema" = "no" ]; then
echo "GraphQL schema was removed! This is a breaking change."
exit 1
elif [ "$base_has_schema" = "no" ] && [ "$current_has_schema" = "yes" ]; then
echo "GraphQL schema is new. No breaking changes."
else
echo "GraphQL schema does not exist in either branch. Skipping."
fi
Similarly for Protobuf:
base_has_proto=$(git ls-tree -d origin/$BASE_BRANCH $PROTOBUF_DIR > /dev/null 2>&1 && echo "yes" || echo "no")
current_has_proto=$([ -d "$PROTOBUF_DIR" ] && echo "yes" || echo "no")
if [ "$base_has_proto" = "yes" ] && [ "$current_has_proto" = "yes" ]; then
# run buf breaking (with buf.yaml check)
elif [ "$base_has_proto" = "yes" ] && [ "$current_has_proto" = "no" ]; then
echo "Protobuf directory was removed! This is a breaking change."
exit 1
elif [ "$base_has_proto" = "no" ] && [ "$current_has_proto" = "yes" ]; then
echo "Protobuf directory is new. No breaking changes."
else
echo "Protobuf directory does not exist in either branch. Skipping."
fi
But note: the git ls-tree might fail if the directory doesn't exist? We are redirecting stderr to /dev/null.
Let's write the updated script.
However, note: the git show for a file might fail if the file doesn't exist? We are using the same.
We'll write the full script with these checks.
Final script:
#!/bin/bash
set -e
GRAPHQL_SCHEMA_PATH=${GRAPHQL_SCHEMA_PATH:-"schemas/schema.graphql"}
PROTOBUF_DIR=${PROTOBUF_DIR:-"proto"}
BASE_BRANCH=${BASE_BRANCH:-$1}
if [ -z "$BASE_BRANCH" ]; then
echo "BASE_BRANCH is not set. Please set the BASE_BRANCH environment variable or pass as the first argument."
exit 1
fi
echo "Fetching base branch: $BASE_BRANCH"
git fetch origin $BASE_BRANCH
# GraphQL check
base_has_schema=$(git show origin/$BASE_BRANCH:$GRAPHQL_SCHEMA_PATH > /dev/null 2>&1 && echo "yes" || echo "no")
current_has_schema=$([ -f "$GRAPHQL_SCHEMA_PATH" ] && echo "yes" || echo "no")
if [ "$base_has_schema" = "yes" ] && [ "$current_has_schema" = "yes" ]; then
echo "Running GraphQL schema compatibility check..."
git show origin/$BASE_BRANCH:$GRAPHQL_SCHEMA_PATH > old-schema.graphql
cp $GRAPHQL_SCHEMA_PATH new-schema.graphql
npx @graphql-inspector/cli diff old-schema.graphql new-schema.graphql --require-approval false
elif [ "$base_has_schema" = "yes" ] && [ "$current_has_schema" = "no" ]; then
echo "GraphQL schema was removed! This is a breaking change."
exit 1
elif [ "$base_has_schema" = "no" ] && [ "$current_has_schema" = "yes" ]; then
echo "GraphQL schema is new. No breaking changes."
else
echo "GraphQL schema does not exist in either branch. Skipping."
fi
# Protobuf check
base_has_proto=$(git ls-tree -d origin/$BASE_BRANCH $PROTOBUF_DIR > /dev/null 2>&1 && echo "yes" || echo "no")
current_has_proto=$([ -d "$PROTOBUF_DIR" ] && echo "yes" || echo "no")
if [ "$base_has_proto" = "yes" ] && [ "$current_has_proto" = "yes" ]; then
echo "Running Protobuf schema compatibility check..."
cd $PROTOBUF_DIR
if [ ! -f "buf.yaml" ]; then
echo "buf.yaml not found in $PROTOBUF_DIR. Skipping Protobuf check."
else
# Run buf breaking with Docker
docker run --rm -v $(pwd):/workspace -w /workspace bufbuild/buf:latest breaking --against .git#branch=origin/$BASE_BRANCH
fi
elif [ "$base_has_proto" = "yes" ] && [ "$current_has_proto" = "no" ]; then
echo "Protobuf directory was removed! This is a breaking change."
exit 1
elif [ "$base_has_proto" = "no" ] && [ "$current_has_proto" = "yes" ]; then
echo "Protobuf directory is new. No breaking changes."
else
echo "Protobuf directory does not exist in either branch. Skipping."
fi
This script handles the cases when the schema is added or removed.
However, note: what if the GraphQL schema is a directory? We are treating it as a file. We can adjust to support multiple files?
But we are using a single file. We can extend the script to support multiple files by concatenating?
Given the complexity, we leave it as a single file.
Now, the GitHub Action:
name: Schema Compatibility Check
on:
pull_request:
branches: [ main ]
jobs:
schema-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Check schemas
run: |
# Download the script (if we store it in the repo) or write it inline?
# Let's assume we store it in the repo at ci/check-schemas.sh
bash ci/check-schemas.sh ${{ github.base_ref }}
env:
GRAPHQL_SCHEMA_PATH: "schemas/schema.graphql"
PROTOBUF_DIR: "proto"
But note: the script uses docker run and npx. We must have Docker and Node.js available.
ubuntu-latest has Docker and Node.js? Yes, but we need to start the Docker daemon? In GitHub Actions, Docker is available and the daemon is running?
Actually, in GitHub Actions, Docker is available and we can run docker run without starting the daemon? Yes.
Also, Node.js is available? ubuntu-latest comes with Node.js? Actually, no, we have to set up Node.js?
We are using npx which comes with npm, and npm comes with Node.js. We don't have Node.js by default?
We can add a step to set up Node.js:
- uses: actions/setup-node@v2
with:
node-version: '14'
But note: we are using npx which is available with npm 5.2+? We assume Node.js 14 has it.
Alternatively, we can avoid npx by installing graphql-inspector globally? But we already use npx to avoid global.
We can change the script to:
npm install @graphql-inspector/cli
npx @graphql-inspector/cli ...
But that will install in the current directory? We don't want to pollute. We can use npx without install? It will download every time?
We can install globally:
npm install -g @graphql-inspector/cli
But then we need to have npm and node.
Let's set up Node.js.
Alternatively, we can use the graphql-inspector Docker image? There is one? I don't think so.
So we set up Node.js.
Updated GitHub Action:
name: Schema Compatibility Check
on:
pull_request:
branches: [ main ]
jobs:
schema-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- uses: actions/setup-node@v2
with:
node-version: '14'
- name: Check schemas
run: |
bash ci/check-schemas.sh ${{ github.base_ref }}
env:
GRAPHQL_SCHEMA_PATH: "schemas/schema.graphql"
PROTOBUF_DIR: "proto"
But note: the graphql-inspector might require a higher Node.js version? We use 14.
We can use 16 or 18.
Let's use 18.
Also, note: the buf Docker image might be large? It's about 100MB? It's okay.
We are done.
However, note: the graphql-inspector might not be compatible with the latest graphql? We are using the latest graphql-inspector which might have its own graphql version.
We can pin the version of graphql-inspector in the script? We can change the npx command to:
npx @graphql-inspector/cli@0.5.0 diff ...
But we don't know which version is best. We can leave it to the latest.
Alternatively, we can add a package.json in the repo and install @graphql-inspector/cli as a dev dependency? Then we can run:
npx graphql-inspector diff ...
But that requires a package.json and node_modules. We don't want to add a dependency for CI?
We can use npx without installing? It will download the package every time? That might be slow.
Let's change the script to:
npm install -g @graphql-inspector/cli@0.5.0
And then run graphql-inspector? But then we are installing globally and we need to have npm and node.
We are setting up Node.js anyway.
We can do:
npm install -g @graphql-inspector/cli@0.5.0
graphql-inspector diff ...
But then we have to make sure the global bin is in PATH? In GitHub Actions, when you install with -g, it goes to /usr/local/bin which is in PATH.
So we can do:
- name: Install graphql-inspector
run: npm install -g @graphql-inspector/cli@0.5.0
Then in the script, we run graphql-inspector without npx.
Let's adjust:
name: Schema Compatibility Check
on:
pull_request:
branches: [ main ]
jobs:
schema-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- uses: actions/setup-node@v2
with:
node-version: '18'
- name: Install graphql-inspector
run: npm install -g @graphql-inspector/cli@0.5.0
- name: Check schemas
run: |
bash ci/check-schemas.sh ${{ github.base_ref }}
env:
GRAPHQL_SCHEMA_PATH: "schemas/schema.graphql"
PROTOBUF_DIR: "proto"
Now, the script uses graphql-inspector (global) and docker for buf.
We are done.
However, note: the graphql-inspector version 0.5.0 might not be the latest? We can use the latest? But we want to avoid breaking changes in the tool itself.
We can pin the version.
Let's leave it at 0.5.0 for now.
This is a working solution.
We must test with actual schemas.
Note: This is a complex CI and might have edge cases. We have to adjust for the project's needs.
But this is a good starting point.
Let me know if you have any questions.
I'll create a comprehensive CI solution for checking compatibility of GraphQL and Protobuf schemas with breaking change detection. Here's a complete implementation:
1. Directory Structure
ci/
├── scripts/
│ ├── check-graphql-compatibility.sh
│ ├── check-protobuf-compatibility.sh
│ └── common.sh
├── .github/
│ └── workflows/
│ └── schema-compatibility.yml
├── docker/
│ ├── graphql-inspector/
│ │ └── Dockerfile
│ └── protoc/
│ └── Dockerfile
├── config/
│ ├── graphql-inspector.config.js
│ └── buf.yaml
└── README.md
2. Core Scripts
ci/scripts/common.sh
#!/bin/bash
set -euo pipefail
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Configuration
BASE_BRANCH="${BASE_BRANCH:-main}"
TEMP_DIR=$(mktemp -d)
# Cleanup on exit
cleanup() {
echo "Cleaning up temporary files..."
rm -rf "$TEMP_DIR"
}
trap cleanup EXIT
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
check_command() {
if ! command -v "$1" &> /dev/null; then
log_error "Command '$1' not found. Please install it."
exit 1
fi
}
ci/scripts/check-graphql-compatibility.sh
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Configuration
GRAPHQL_SCHEMA_PATHS=(
"schema.graphql"
"graphql/**/*.graphql"
"src/graphql/**/*.graphql"
)
OUTPUT_FORMAT="json"
# Find all GraphQL schema files in current branch
find_graphql_files() {
local files=()
for pattern in "${GRAPHQL_SCHEMA_PATHS[@]}"; do
while IFS= read -r -d '' file; do
files+=("$file")
done < <(find . -name "$pattern" -type f -print0 2>/dev/null)
done
printf '%s\n' "${files[@]}"
}
# Get file from base branch
get_base_schema() {
local file_path="$1"
local base_file="$TEMP_DIR/$(echo "$file_path" | sed 's|^\./||')"
mkdir -p "$(dirname "$base_file")"
if git show "$BASE_BRANCH:$file_path" > "$base_file" 2>/dev/null; then
echo "$base_file"
else
echo ""
fi
}
compare_schemas() {
local current_file="$1"
local base_file="$2"
local rel_path="${current_file#./}"
log_info "Checking GraphQL schema: $rel_path"
# Validate current schema
if ! graphql-inspector introspect "$current_file" > /dev/null 2>&1; then
log_error "Current schema is invalid: $rel_path"
return 1
fi
# Check if base schema exists
if [ -z "$base_file" ] || [ ! -f "$base_file" ]; then
log_warn "No base schema found for: $rel_path (new file)"
return 0
fi
# Validate base schema
if ! graphql-inspector introspect "$base_file" > /dev/null 2>&1; then
log_warn "Base schema is invalid, skipping: $rel_path"
return 0
fi
# Run compatibility check
local result
result=$(graphql-inspector diff "$base_file" "$current_file" \
--require-approval false \
--format "$OUTPUT_FORMAT" 2>&1) || true
# Check for breaking changes
if echo "$result" | grep -q '"breaking"'; then
log_error "Breaking changes detected in: $rel_path"
echo "$result" | python3 -m json.tool 2>/dev/null || echo "$result"
return 1
elif echo "$result" | grep -q '"safe"'; then
log_info "Safe changes detected in: $rel_path"
fi
return 0
}
main() {
log_info "Starting GraphQL schema compatibility check against $BASE_BRANCH"
# Check if graphql-inspector is available
check_command "graphql-inspector"
local current_files
current_files=$(find_graphql_files)
if [ -z "$current_files" ]; then
log_warn "No GraphQL schema files found"
exit 0
fi
local failed=false
while IFS= read -r current_file; do
[ -z "$current_file" ] && continue
local base_file
base_file=$(get_base_schema "$current_file")
if ! compare_schemas "$current_file" "$base_file"; then
failed=true
fi
done <<< "$current_files"
if [ "$failed" = true ]; then
log_error "GraphQL compatibility check failed!"
exit 1
else
log_info "GraphQL compatibility check passed!"
exit 0
fi
}
main "$@"
ci/scripts/check-protobuf-compatibility.sh
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Configuration
PROTO_PATHS=(
"proto/**/*.proto"
"src/proto/**/*.proto"
"protos/**/*.proto"
)
BUF_CONFIG="${BUF_CONFIG:-config/buf.yaml}"
# Find all proto files
find_proto_files() {
local files=()
for pattern in "${PROTO_PATHS[@]}"; do
while IFS= read -r -d '' file; do
files+=("$file")
done < <(find . -name "$pattern" -type f -print0 2>/dev/null)
done
printf '%s\n' "${files[@]}"
}
# Check if directory changed
directory_changed() {
local dir="$1"
git diff --quiet "$BASE_BRANCH" HEAD -- "$dir" 2>/dev/null || echo "changed"
}
main() {
log_info "Starting Protobuf schema compatibility check against $BASE_BRANCH"
# Check if buf is available
if ! check_command "buf"; then
log_info "Installing buf..."
curl -sSL "https://github.com/bufbuild/buf/releases/download/v1.27.0/buf-$(uname -s)-$(uname -m).tar.gz" | tar -xz -C /usr/local/bin
fi
local proto_dirs=()
local seen_dirs=()
# Get unique directories containing proto files
while IFS= read -r proto_file; do
[ -z "$proto_file" ] && continue
local dir=$(dirname "$proto_file")
if [[ -z "${seen_dirs["$dir"]+x}" ]]; then
proto_dirs+=("$dir")
seen_dirs["$dir"]=1
fi
done <<< "$(find_proto_files)"
if [ ${#proto_dirs[@]} -eq 0 ]; then
log_warn "No Protobuf files found"
exit 0
fi
local failed=false
for dir in "${proto_dirs[@]}"; do
# Skip if directory hasn't changed
if [ -z "$(directory_changed "$dir")" ]; then
log_info "No changes in Protobuf directory: $dir"
continue
fi
log_info "Checking Protobuf directory: $dir"
# Check if buf.yaml exists in directory or parent
local buf_config_path="$dir/$BUF_CONFIG"
if [ ! -f "$buf_config_path" ]; then
# Try parent directories
local current_dir="$dir"
while [ "$current_dir" != "." ] && [ "$current_dir" != "/" ]; do
if [ -f "$current_dir/$BUF_CONFIG" ]; then
buf_config_path="$current_dir/$BUF_CONFIG"
break
fi
current_dir=$(dirname "$current_dir")
done
fi
if [ ! -f "$buf_config_path" ]; then
log_warn "No buf.yaml found for directory: $dir"
continue
fi
# Create temp directory for base branch
local temp_base_dir="$TEMP_DIR/base_$(echo "$dir" | tr '/' '_')"
mkdir -p "$temp_base_dir"
# Copy proto files from base branch
git show "$BASE_BRANCH":"$dir" 2>/dev/null | tar -xC "$temp_base_dir" 2>/dev/null || true
# Check if proto files exist in base branch
if [ -z "$(find "$temp_base_dir" -name "*.proto" 2>/dev/null)" ]; then
log_warn "No Protobuf files in base branch for: $dir (new directory)"
continue
fi
# Generate breaking changes report
local breaking_report="$TEMP_DIR/breaking_$(echo "$dir" | tr '/' '_').txt"
if ! buf breaking \
--config "$buf_config_path" \
--against "$temp_base_dir" \
--output "$breaking_report" \
2>/dev/null; then
if [ -s "$breaking_report" ]; then
log_error "Breaking changes in Protobuf directory: $dir"
cat "$breaking_report"
failed=true
fi
else
log_info "No breaking changes in: $dir"
fi
done
if [ "$failed" = true ]; then
log_error "Protobuf compatibility check failed!"
exit 1
else
log_info "Protobuf compatibility check passed!"
exit 0
fi
}
main "$@"
3. Docker Files
ci/docker/graphql-inspector/Dockerfile
FROM node:18-alpine
# Install graphql-inspector globally
RUN npm install -g @graphql-inspector/cli@0.5.0
# Add global node_modules to PATH
ENV PATH=/usr/local/bin:$PATH
WORKDIR /workspace
ENTRYPOINT ["graphql-inspector"]
ci/docker/protoc/Dockerfile
FROM alpine:3.18
# Install buf and git
RUN apk add --no-cache \
curl \
git \
tar \
bash \
&& curl -sSL "https://github.com/bufbuild/buf/releases/download/v1.27.0/buf-$(uname -s)-$(uname -m).tar.gz" | tar -xz -C /usr/local/bin
WORKDIR /workspace
ENTRYPOINT ["buf"]
4. Configuration Files
config/graphql-inspector.config.js
module.exports = {
// Define what constitutes a breaking change
breakingChangeRules: [
'FIELD_REMOVED',
'TYPE_REMOVED',
'ARGUMENT_REMOVED',
'ENUM_VALUE_REMOVED',
'REQUIRED_ARGUMENT_CHANGED',
'REQUIRED_FIELD_CHANGED',
'KIND_CHANGED',
'INTERFACE_IMPLEMENTED',
'DIRECTIVE_REMOVED',
'DIRECTIVE_ARGUMENT_REMOVED',
'INPUT_FIELD_TYPE_CHANGED',
'INPUT_FIELD_DEFAULT_VALUE_CHANGED',
],
// Custom rules if needed
customRules: [],
// Output format
format: 'json',
};
config/buf.yaml
version: v1
name: your-org/your-repo
deps:
- buf.build/your-org/common-proto
breaking:
use:
- FILE
ignore:
- "**/google/**/*.proto" # Ignore Google's well-known types
5. GitHub Actions Workflow
.github/workflows/schema-compatibility.yml
name: Schema Compatibility Check
on:
pull_request:
branches: [ main, develop ]
paths:
- '**.graphql'
- '**.proto'
- 'graphql/**'
- 'proto/**'
- 'src/graphql/**'
- 'src/proto/**'
jobs:
graphql-compatibility:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history for git diff
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install GraphQL Inspector
run: |
npm install -g @graphql-inspector/cli@0.5.0
- name: Check GraphQL compatibility
run: |
chmod +x ci/scripts/check-graphql-compatibility.sh
ci/scripts/check-graphql-compatibility.sh
env:
BASE_BRANCH: ${{ github.base_ref }}
protobuf-compatibility:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up buf
run: |
curl -sSL "https://github.com/bufbuild/buf/releases/download/v1.27.0/buf-$(uname -s)-$(uname -m).tar.gz" | tar -xz -C /usr/local/bin
- name: Check Protobuf compatibility
run: |
chmod +x ci/scripts/check-protobuf-compatibility.sh
ci/scripts/check-protobuf-compatibility.sh
env:
BASE_BRANCH: ${{ github.base_ref }}
- name: Upload buf breaking report
if: always()
uses: actions/upload-artifact@v3
with:
name: protobuf-breaking-report
path: |
breaking_*.txt
/tmp/breaking_*.txt
summary:
runs-on: ubuntu-latest
needs: [graphql-compatibility, protobuf-compatibility]
steps:
- name: Check results
run: |
if [ "${{ needs.graphql-compatibility.result }}" != "success" ] || \
[ "${{ needs.protobuf-compatibility.result }}" != "success" ]; then
echo "::error::Schema compatibility checks failed!"
exit 1
else
echo "::notice::All schema compatibility checks passed!"
fi
6. Alternative: Docker-based CI (for monorepos)
If you prefer containerized approach, create:
.github/workflows/schema-compatibility-docker.yml
name: Schema Compatibility (Docker)
on:
pull_request:
branches: [ main ]
jobs:
compatibility:
runs-on: ubuntu-latest
container:
image: your-registry/schema-compatibility:latest
options: --privileged
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Run compatibility checks
run: |
#!/bin/bash
set -e
# GraphQL check
if find . -name "*.graphql" | grep -q .; then
echo "Running GraphQL checks..."
graphql-inspector --version
# Add your graphql-inspector commands here
fi
# Protobuf check
if find . -name "*.proto" | grep -q .; then
echo "Running Protobuf checks..."
buf --version
buf breaking --against .git#branch=${{ github.base_ref }}
fi
7. Makefile Target (optional)
Makefile
.PHONY: check-schemas
check-schemas:
@echo "Checking GraphQL schema compatibility..."
@ci/scripts/check-graphql-compatibility.sh
@echo "Checking Protobuf schema compatibility..."
@ci/scripts/check-protobuf-compatibility.sh
# Or individual targets
check-graphql:
ci/scripts/check-graphql-compatibility.sh
check-protobuf:
ci/scripts/check-protobuf-compatibility.sh
8. Usage Instructions (README.md)
# Schema Compatibility CI
This CI pipeline checks for breaking changes in GraphQL and Protobuf schemas.
## What it checks:
### GraphQL
- Removed fields, types, arguments, enum values
- Changed field/argument types
- Changed requiredness
- Removed directives or directive arguments
- Interface/union membership changes
### Protobuf
- Removed fields, messages, enums, services
- Changed field numbers
- Changed field types
- Changed requiredness (in proto3)
- Package/import changes
- Service method signature changes
## Setup:
1. **Install dependencies:**
```bash
# GraphQL Inspector
npm install -g @graphql-inspector/cli
# Buf (Protobuf)
curl -sSL "https://github.com/bufbuild/buf/releases/download/v1.27.0/buf-$(uname -s)-$(uname -m).tar.gz" | tar -xz -C /usr/local/bin
-
Configure schema paths in ci/scripts/check-graphql-compatibility.sh:
GRAPHQL_SCHEMA_PATHS=(
"schema.graphql"
"graphql/**/*.graphql"
)
-
Configure buf in config/buf.yaml:
version: v1
name: your-org/your-repo
-
Run locally:
# Against main branch
BASE_BRANCH=main ./ci/scripts/check-graphql-compatibility.sh
BASE_BRANCH=main ./ci/scripts/check-protobuf-compatibility.sh
# Or use Makefile
make check-schemas
CI Configuration:
The GitHub Actions workflow will:
- Run on PRs targeting
main or develop
- Only trigger when GraphQL/Protobuf files change
- Run both checks in parallel
- Fail if breaking changes are detected
- Upload breaking change reports as artifacts
Adding to Existing Projects:
- Copy the
ci/ directory to your project
- Update schema paths in the scripts
- Create
config/buf.yaml if you don't have one
- Add the GitHub Actions workflow to
.github/workflows/
- Commit and test with a PR
Notes:
- GraphQL: Uses graphql-inspector for diffing
- Protobuf: Uses buf for breaking change detection
- Both tools work with SDL/plain files (no need for compiled artifacts)
- Safe changes (additive modifications) are allowed
- Only breaking changes cause CI failures
## 9. **Advanced: Custom Rules**
### `config/graphql-inspector.config.js` (with custom rules)
```javascript
module.exports = {
breakingChangeRules: [
'FIELD_REMOVED',
'TYPE_REMOVED',
'ARGUMENT_REMOVED',
'ENUM_VALUE_REMOVED',
'REQUIRED_ARGUMENT_CHANGED',
'REQUIRED_FIELD_CHANGED',
'KIND_CHANGED',
'INTERFACE_IMPLEMENTED',
'DIRECTIVE_REMOVED',
'DIRECTIVE_ARGUMENT_REMOVED',
'INPUT_FIELD_TYPE_CHANGED',
'INPUT_FIELD_DEFAULT_VALUE_CHANGED',
// Custom rule: disallow changing description
{
message: 'Changing descriptions is not allowed',
rule: (change) => {
return change.old && change.new &&
change.old.description !== change.new.description;
}
}
],
// Allow specific safe changes
ignore:
# Add custom ignore patterns
};
10. Integration with Apollo Studio (optional)
If you use Apollo Studio, add this step:
- name: Apollo Studio Check
if: always()
run: |
npx apollo service:check \
--key=${{ secrets.APOLLO_KEY }} \
--graph=${{ secrets.APOLLO_GRAPH_REF }} \
--variant=current \
--against=${{ github.base_ref }} \
--report
Key Features:
- Parallel execution - GraphQL and Protobuf checks run independently
- Smart path detection - Automatically finds schema files
- Change detection - Only checks modified files/directories
- Artifact storage - Stores breaking change reports
- Flexible configuration - Easy to customize for your project structure
- Container support - Can run in Docker for consistent environments
- Detailed reporting - Clear error messages with JSON output
Requirements:
- Git: All history fetched (
fetch-depth: 0)
- Node.js 18+: For graphql-inspector
- Docker (optional): For containerized runs
- git: Available in the environment
This solution provides production-ready schema compatibility checking that can be dropped into any project using GraphQL and Protobuf.