Skip to content

feat: add validation to protographic#2108

Merged
Noroth merged 5 commits intomainfrom
ludwig/eng-7712-pre-check-the-graphql-schema-in-protographic
Aug 5, 2025
Merged

feat: add validation to protographic#2108
Noroth merged 5 commits intomainfrom
ludwig/eng-7712-pre-check-the-graphql-schema-in-protographic

Conversation

@Noroth
Copy link
Copy Markdown
Contributor

@Noroth Noroth commented Aug 5, 2025

Summary by CodeRabbit

  • New Features

    • Added validation of GraphQL schemas before generating mapping and proto files, with detailed console output for warnings and errors.
    • Introduced formatted display of validation results, including clear messaging for warnings (generation continues) and errors (generation stops).
    • Added new GraphQL schema fixtures to test various validation scenarios, including warnings and errors.
    • Expanded support for federation entity lookups with multiple and compound keys in schema processing.
    • Added a new exported function to validate GraphQL SDL schemas with configurable rules.
  • Bug Fixes

    • Improved handling of invalid schemas by halting generation when validation errors are detected.
  • Tests

    • Added comprehensive tests to verify schema validation behavior, ensuring correct handling and messaging for warnings and errors during generation.
    • Introduced dedicated tests for the new SDL validation logic.
  • Documentation

    • Enhanced console output to clearly communicate schema validation issues to end-users.
    • Updated documentation to reflect expanded support and limitations for schema features in proto generation.

Checklist

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 5, 2025

Walkthrough

This change introduces a GraphQL SDL validation step into the gRPC service and router plugin code generation workflows. It adds a modular SDL validation framework with configurable rules, a function to render validation results in the console, and several new schema fixtures and tests to verify handling of warnings and errors. The validation logic is encapsulated in a new visitor class, with corresponding exports and comprehensive test coverage.

Changes

Cohort / File(s) Change Summary
gRPC Service & Router Plugin: Schema Validation Integration
cli/src/commands/grpc-service/commands/generate.ts, cli/src/commands/router/commands/plugin/toolchain.ts
Added schema validation step before file generation using validateGraphQLSDL, rendering results with renderValidationResults, and updating spinner text for validation. No changes to public API signatures.
Validation Results Rendering Utility
cli/src/commands/router/commands/plugin/helper.ts
Added renderValidationResults function to format and display schema validation warnings and errors in the console, halting generation on errors.
GraphQL SDL Validation Core
protographic/src/sdl-validation-visitor.ts, protographic/src/index.ts
Introduced SDLValidationVisitor class for AST-based schema validation, supporting configurable rules and collecting warnings/errors. Added validateGraphQLSDL function and re-exported validation types and visitor.
Schema Fixtures for Testing
cli/test/fixtures/schema-with-nullable-list-items.graphql, cli/test/fixtures/schema-with-validation-errors.graphql, cli/test/fixtures/schema-with-warnings-and-errors.graphql
Added new GraphQL schema files designed to trigger validation warnings, errors, or both, for use in tests.
gRPC Service Command Tests
cli/test/grpc-service.test.ts
Added tests to verify generation behavior with schemas containing warnings, errors, or both. Tests assert on file outputs and console logs. Updated imports and fixture path resolution to use absolute paths.
SDL Validation Visitor Tests
protographic/tests/sdl-validation/01-basic-validation.test.ts
Added comprehensive tests for the SDLValidationVisitor, covering detection of warnings, errors, and correct handling of various schema features.
Documentation Update
protographic/SDL_PROTO_RULES.md
Updated documentation to reflect new supported features and limitations in SDL to Protobuf conversion, including support for multiple and compound keys, nullable scalars, lists, and nested lists, and added limitation for nullable list items.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

  • Complexity: High. The SDL validation visitor introduces a new modular validation framework with AST traversal, rule configuration, and context-aware error/warning reporting. Integration into code generation flows and extensive new tests (unit and integration) require careful review.
  • Scope: Multiple core modules, new utility functions, new test fixtures, and both CLI and library-level changes.
  • Volume: Moderate to high, with several new files and significant logic in the validation visitor and tests.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b7d644 and c382cd7.

📒 Files selected for processing (1)
  • protographic/SDL_PROTO_RULES.md (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • protographic/SDL_PROTO_RULES.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ludwig/eng-7712-pre-check-the-graphql-schema-in-protographic

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🔭 Outside diff range comments (1)
protographic/src/index.ts (1)

1-112: Fix code formatting issues.

The pipeline indicates Prettier formatting check failed. Please run prettier --write to fix the code style issues before merging.

🧹 Nitpick comments (3)
protographic/tests/sdl-validation/01-basic-validation.test.ts (1)

1-3: Remove unused import

The buildSchema import from graphql is not used anywhere in this test file.

-import { buildSchema } from 'graphql';
import { describe, expect, test } from 'vitest';
import { SDLValidationVisitor } from '../../src/sdl-validation-visitor';
cli/test/grpc-service.test.ts (1)

193-195: Remove empty line for consistency

Remove the empty line to match the formatting in other test cases.

     const originalConsoleLog = console.log;
     const consoleOutput: string[] = [];
-    
     console.log = (...args: any[]) => {
protographic/src/sdl-validation-visitor.ts (1)

120-137: Remove unnecessary null check

The GraphQL parse() function throws an error on invalid input rather than returning null, making the null check unnecessary.

   public visit(): ValidationResult {
     try {
       const astNode = parse(this.schema);
-      if (!astNode) {
-        throw new Error('Schema parsing resulted in null AST');
-      }

       const visitor = this.createASTVisitor();
       visit(astNode, visitor);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7591878 and 8510b06.

📒 Files selected for processing (10)
  • cli/src/commands/grpc-service/commands/generate.ts (2 hunks)
  • cli/src/commands/router/commands/plugin/helper.ts (2 hunks)
  • cli/src/commands/router/commands/plugin/toolchain.ts (3 hunks)
  • cli/test/fixtures/schema-with-nullable-list-items.graphql (1 hunks)
  • cli/test/fixtures/schema-with-validation-errors.graphql (1 hunks)
  • cli/test/fixtures/schema-with-warnings-and-errors.graphql (1 hunks)
  • cli/test/grpc-service.test.ts (4 hunks)
  • protographic/src/index.ts (2 hunks)
  • protographic/src/sdl-validation-visitor.ts (1 hunks)
  • protographic/tests/sdl-validation/01-basic-validation.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: SkArchon
PR: wundergraph/cosmo#2067
File: router/pkg/config/config.schema.json:1637-1644
Timestamp: 2025-07-21T15:06:36.664Z
Learning: In the Cosmo router project, when extending JSON schema validation for security-sensitive fields like JWKS secrets, backwards compatibility is maintained by implementing warnings in the Go code rather than hard validation constraints in the schema. This allows existing configurations to continue working while alerting users to potential security issues.
Learnt from: SkArchon
PR: wundergraph/cosmo#2067
File: router/pkg/authentication/jwks_token_decoder.go:80-106
Timestamp: 2025-07-21T14:46:34.879Z
Learning: In the Cosmo router project, required field validation for JWKS configuration (Secret, Algorithm, KeyId) is handled at the JSON schema level in config.schema.json rather than through runtime validation in the Go code at router/pkg/authentication/jwks_token_decoder.go.
Learnt from: SkArchon
PR: wundergraph/cosmo#1929
File: router/internal/circuit/manager.go:16-25
Timestamp: 2025-06-30T20:39:02.387Z
Learning: In the Cosmo router project, parameter validation for circuit breaker configuration is handled at the JSON schema level rather than through runtime validation methods on structs. The config.schema.json file contains comprehensive validation constraints for circuit breaker parameters.
📚 Learning: in the cosmo router project, required field validation for jwks configuration (secret, algorithm, ke...
Learnt from: SkArchon
PR: wundergraph/cosmo#2067
File: router/pkg/authentication/jwks_token_decoder.go:80-106
Timestamp: 2025-07-21T14:46:34.879Z
Learning: In the Cosmo router project, required field validation for JWKS configuration (Secret, Algorithm, KeyId) is handled at the JSON schema level in config.schema.json rather than through runtime validation in the Go code at router/pkg/authentication/jwks_token_decoder.go.

Applied to files:

  • cli/src/commands/grpc-service/commands/generate.ts
  • cli/src/commands/router/commands/plugin/toolchain.ts
📚 Learning: in the cosmo router project, when extending json schema validation for security-sensitive fields lik...
Learnt from: SkArchon
PR: wundergraph/cosmo#2067
File: router/pkg/config/config.schema.json:1637-1644
Timestamp: 2025-07-21T15:06:36.664Z
Learning: In the Cosmo router project, when extending JSON schema validation for security-sensitive fields like JWKS secrets, backwards compatibility is maintained by implementing warnings in the Go code rather than hard validation constraints in the schema. This allows existing configurations to continue working while alerting users to potential security issues.

Applied to files:

  • cli/src/commands/router/commands/plugin/helper.ts
  • cli/src/commands/router/commands/plugin/toolchain.ts
  • cli/test/fixtures/schema-with-warnings-and-errors.graphql
🧬 Code Graph Analysis (2)
protographic/src/index.ts (1)
protographic/src/sdl-validation-visitor.ts (2)
  • ValidationResult (18-23)
  • SDLValidationVisitor (59-414)
cli/src/commands/router/commands/plugin/toolchain.ts (2)
protographic/src/index.ts (1)
  • validateGraphQLSDL (88-91)
cli/src/commands/router/commands/plugin/helper.ts (1)
  • renderValidationResults (75-132)
🪛 GitHub Actions: Protographic CI
protographic/src/index.ts

[warning] 1-1: Prettier formatting check failed. Code style issues found. Run 'prettier --write' to fix code style issues.

protographic/src/sdl-validation-visitor.ts

[warning] 1-1: Prettier formatting check failed. Code style issues found. Run 'prettier --write' to fix code style issues.

🪛 GitHub Actions: wgc CI
cli/src/commands/router/commands/plugin/helper.ts

[warning] 1-1: Prettier formatting check failed. Code style issues found. Run Prettier with --write to fix.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (28)
cli/src/commands/grpc-service/commands/generate.ts (3)

2-7: LGTM! Clean import addition.

The validateGraphQLSDL function is properly imported from the protographic module alongside existing functions.


13-13: LGTM! Proper helper function import.

The renderValidationResults import is correctly added from the helper module.


130-136: Excellent validation integration!

The validation step is well-positioned in the workflow and properly integrated:

  • Validates after schema reading but before generation
  • Provides clear user feedback via spinner
  • Uses the validation results rendering for consistent output
  • Follows the established pattern where errors halt generation while warnings allow continuation
protographic/src/index.ts (3)

7-7: LGTM! Proper import of validation components.

The import correctly brings in the SDLValidationVisitor class and ValidationResult type needed for the validation functionality.


81-91: Well-implemented validation function!

The validateGraphQLSDL function has a clean implementation:

  • Clear and focused responsibility (validate GraphQL SDL)
  • Proper error handling documentation
  • Consistent with the module's patterns
  • Matches the usage pattern in the CLI integration

96-96: LGTM! Necessary exports for validation functionality.

The exports properly expose the SDLValidationVisitor class and ValidationResult type for external use, following the established patterns in the module.

Also applies to: 100-100

cli/test/fixtures/schema-with-nullable-list-items.graphql (1)

1-18: Well-designed test fixture for validation testing.

This schema fixture effectively tests the nullable list items validation:

  • Contains realistic GraphQL schema structure
  • The tags: [String]! field on line 12 properly demonstrates nullable items in a non-nullable list
  • Will appropriately trigger validation warnings without causing errors
  • Good balance of different field types for comprehensive testing
cli/src/commands/router/commands/plugin/toolchain.ts (3)

7-12: LGTM! Consistent import additions.

The imports properly add the validation functionality with the same pattern used in the gRPC service generation command, ensuring consistency across workflows.

Also applies to: 17-17


368-369: Good refactoring for better code organization.

Storing the schema file path in a variable improves readability and enables its reuse for validation result rendering.


384-387: Excellent consistency with gRPC service validation!

The validation implementation mirrors the gRPC service generation command perfectly:

  • Same workflow positioning (after schema reading, before generation)
  • Same user feedback via spinner updates
  • Same validation and rendering function calls
  • Ensures consistent behavior across both generation workflows
cli/test/fixtures/schema-with-warnings-and-errors.graphql (1)

1-16: Excellent comprehensive validation test fixture!

This schema effectively tests the complete validation workflow:

  • Warnings: Lines 3-4 with nullable list items ([String], [User]) will trigger nullable-items-in-list-types warnings
  • Errors: Line 13 with nested key directive (@key(fields: "id nested { name }")) will trigger nested-key-directives error
  • Documentation: Comments clearly explain expected validation behavior
  • Realism: Represents a practical schema structure that validates real-world scenarios

Perfect for testing both individual validation rules and their interaction.

protographic/tests/sdl-validation/01-basic-validation.test.ts (5)

6-18: LGTM!

Basic validation test is well-structured and covers the happy path scenario correctly.


59-72: LGTM!

Test correctly validates that nullable list items generate appropriate warnings.


74-87: LGTM!

Test correctly handles nested list validation scenarios.


89-111: LGTM!

Test correctly validates that nested key directives generate errors as expected.


113-133: LGTM!

Test correctly validates that @requires directive generates appropriate warnings.

cli/test/fixtures/schema-with-validation-errors.graphql (1)

1-13: LGTM!

The fixture correctly implements a schema with nested key directive that will trigger validation errors as intended for testing purposes.

cli/src/commands/router/commands/plugin/helper.ts (2)

1-1: LGTM!

Import is correctly added for the new validation functionality.


75-132: Well-structured validation result renderer

The function provides excellent user experience with:

  • Clear visual hierarchy using tree-like formatting
  • Appropriate use of colors for warnings (yellow) and errors (red)
  • Limiting output to 10 items to avoid overwhelming users
  • Proper error propagation to stop generation on errors
cli/test/grpc-service.test.ts (4)

2-14: LGTM!

Imports are correctly updated to support ES module path resolution for test fixtures.


174-230: LGTM!

Test correctly validates that generation continues with warnings and properly captures/restores console output.


232-290: LGTM!

Test correctly validates that generation fails on errors and no output files are created.


292-357: LGTM!

Test comprehensively validates the behavior when both warnings and errors are present, ensuring proper message ordering and generation failure.

protographic/src/sdl-validation-visitor.ts (5)

1-53: LGTM!

Well-structured imports and interface definitions with comprehensive TypeScript types.


59-76: LGTM!

Clean class setup with proper initialization and documentation.


194-222: LGTM!

The nullable list validation logic correctly handles nested list types and identifies nullable items.


256-277: LGTM!

The key directive validation correctly identifies nested field selections and validates the fields argument type.


303-413: LGTM!

Helper methods are well-implemented with proper null checks and consistent formatting.

Comment thread cli/src/commands/router/commands/plugin/helper.ts
Comment thread protographic/src/sdl-validation-visitor.ts
Comment thread protographic/tests/sdl-validation/01-basic-validation.test.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
protographic/src/sdl-validation-visitor.ts (1)

1-388: Fix Prettier formatting issues

The pipeline indicates formatting issues in this file. Please run Prettier to fix code style.

Run the following command to fix formatting:

npx prettier --write protographic/src/sdl-validation-visitor.ts
🧹 Nitpick comments (1)
protographic/src/sdl-validation-visitor.ts (1)

123-125: Remove unnecessary null check after parse()

The parse() function from GraphQL.js either returns a valid DocumentNode or throws an error. It never returns null or undefined, making this check redundant.

     try {
       const astNode = parse(this.schema);
-      if (!astNode) {
-        throw new Error('Schema parsing resulted in null AST');
-      }

       const visitor = this.createASTVisitor();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8510b06 and 329904c.

📒 Files selected for processing (3)
  • cli/src/commands/router/commands/plugin/helper.ts (2 hunks)
  • protographic/src/index.ts (2 hunks)
  • protographic/src/sdl-validation-visitor.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • protographic/src/index.ts
  • cli/src/commands/router/commands/plugin/helper.ts
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: SkArchon
PR: wundergraph/cosmo#2067
File: router/pkg/config/config.schema.json:1637-1644
Timestamp: 2025-07-21T15:06:36.664Z
Learning: In the Cosmo router project, when extending JSON schema validation for security-sensitive fields like JWKS secrets, backwards compatibility is maintained by implementing warnings in the Go code rather than hard validation constraints in the schema. This allows existing configurations to continue working while alerting users to potential security issues.
Learnt from: SkArchon
PR: wundergraph/cosmo#2067
File: router/pkg/authentication/jwks_token_decoder.go:80-106
Timestamp: 2025-07-21T14:46:34.879Z
Learning: In the Cosmo router project, required field validation for JWKS configuration (Secret, Algorithm, KeyId) is handled at the JSON schema level in config.schema.json rather than through runtime validation in the Go code at router/pkg/authentication/jwks_token_decoder.go.
Learnt from: SkArchon
PR: wundergraph/cosmo#1929
File: router/internal/circuit/manager.go:16-25
Timestamp: 2025-06-30T20:39:02.387Z
Learning: In the Cosmo router project, parameter validation for circuit breaker configuration is handled at the JSON schema level rather than through runtime validation methods on structs. The config.schema.json file contains comprehensive validation constraints for circuit breaker parameters.
📚 Learning: in the protographic sdl validation system, the validation logic for nullable list items only refers ...
Learnt from: Noroth
PR: wundergraph/cosmo#2108
File: protographic/tests/sdl-validation/01-basic-validation.test.ts:20-57
Timestamp: 2025-08-05T13:00:30.255Z
Learning: In the protographic SDL validation system, the validation logic for nullable list items only refers to the actual list type and not the nesting. For example, `[[String!]]` (nullable list of non-nullable lists) would not trigger a nullable list warning because the validation focuses on the immediate list structure rather than nested list structures.

Applied to files:

  • protographic/src/sdl-validation-visitor.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)

Copy link
Copy Markdown
Contributor

@StarpTech StarpTech left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Noroth Noroth merged commit 11a7ddf into main Aug 5, 2025
27 checks passed
@Noroth Noroth deleted the ludwig/eng-7712-pre-check-the-graphql-schema-in-protographic branch August 5, 2025 19:44
@Noroth Noroth mentioned this pull request Sep 30, 2025
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants