Skip to content

feat: add Variables to OperationContext#2045

Merged
alepane21 merged 3 commits intomainfrom
ale/eng-7598-add-variables-to-requestcontextoperation
Jul 15, 2025
Merged

feat: add Variables to OperationContext#2045
alepane21 merged 3 commits intomainfrom
ale/eng-7598-add-variables-to-requestcontextoperation

Conversation

@alepane21
Copy link
Copy Markdown
Contributor

@alepane21 alepane21 commented Jul 14, 2025

As specified in this RFC https://github.com/wundergraph/cosmo/blob/35e80778b0d0f0c51ffcbb4676d17bf711a8aafa/rfc/cosmo-streams-v1.md, we need to provide access to the variables for custom modules.

The operationContext struct already exposes the variables, what is missing is simply adding the corresponding method to the OperationContext interface.

Checklist

Summary by CodeRabbit

  • New Features

    • Added support for accessing operation variables through a new method in the operation context.
    • Introduced a module to capture and verify operation context values during request handling for enhanced testing.
  • Tests

    • Added comprehensive tests to validate operation context values including operation name, type, variables, and client info during GraphQL requests.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 14, 2025

Walkthrough

The OperationContext interface in the core router code was updated to include a new Variables() method. The underlying struct was modified to store a variables field, and a corresponding method implementation was added. Import statements were reordered without affecting functionality. Additionally, a new module VerifyOperationContextValuesModule was introduced to capture and verify operation context values during request handling, accompanied by comprehensive integration tests validating operation context propagation and correctness.

Changes

Files Change Summary
router/core/context.go Added Variables() method to OperationContext interface and operationContext struct; added variables field; reordered imports.
router-tests/modules/verify-operation-context-values/module.go Added new module VerifyOperationContextValuesModule to capture and verify operation context values during request handling.
router-tests/modules/verify_operation_context_values_test.go Added integration tests for VerifyOperationContextValuesModule verifying operation context values for queries and mutations.

📜 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 b827694 and c3c6526.

📒 Files selected for processing (1)
  • router-tests/modules/verify-operation-context-values/module.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • router-tests/modules/verify-operation-context-values/module.go
⏰ 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). (9)
  • GitHub Check: build-router
  • GitHub Check: build_test
  • GitHub Check: build_push_image
  • GitHub Check: integration_test (./events)
  • GitHub Check: image_scan
  • GitHub Check: integration_test (./telemetry)
  • GitHub Check: integration_test (./. ./fuzzquery ./lifecycle ./modules)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jul 14, 2025

Router image scan passed

✅ No security vulnerabilities found in image:

ghcr.io/wundergraph/cosmo/router:sha-cf71f85f5581c344dafe81e510326a4c45511dba

@alepane21 alepane21 force-pushed the ale/eng-7598-add-variables-to-requestcontextoperation branch from 86ceafe to 755cf67 Compare July 14, 2025 16:16
@Noroth
Copy link
Copy Markdown
Contributor

Noroth commented Jul 14, 2025

Do we need some tests here?

@alepane21
Copy link
Copy Markdown
Contributor Author

Do we need some tests here?

I've added some integration tests, thanks for the suggestion!

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: 1

🧹 Nitpick comments (3)
router-tests/modules/verify_operation_context_values_test.go (3)

72-72: Hardcoded normalized query assertion may be brittle.

The assertion uses a hardcoded normalized query string which could break if the GraphQL normalization algorithm changes. Consider using a more flexible approach.

Consider making the content assertion more flexible:

-assert.Equal(t, captured.Content, "query GetEmployee($a: Int!){employee(id: $a){id details {forename surname} tag}}", "Operation content should be set")
+assert.Contains(t, captured.Content, "GetEmployee", "Operation content should contain the operation name")
+assert.Contains(t, captured.Content, "employee(id:", "Operation content should contain the main field")

This makes the test more resilient to changes in query normalization while still verifying the content is meaningful.


189-191: Potential issue with string variable handling.

The test uses GetStringBytes() and converts to string, which might not handle all edge cases like escaped characters or Unicode properly.

Consider using the more direct string access method if available:

-newTagBytes := newTagVar.GetStringBytes()
-assert.Equal(t, "Updated by test", string(newTagBytes), "newTag should be 'Updated by test'")
+assert.Equal(t, "Updated by test", newTagVar.String(), "newTag should be 'Updated by test'")

This approach is more direct and handles string conversion internally.


21-21: Consider extracting common test setup.

The channel creation and configuration setup is duplicated across all three test cases. This could be extracted into a helper function to reduce duplication.

Consider extracting the common setup:

+func setupTestModule(t *testing.T) (chan verifyModule.CapturedOperationValues, config.Config) {
+	resultsChan := make(chan verifyModule.CapturedOperationValues, 1)
+	cfg := config.Config{
+		Graph: config.Graph{},
+		Modules: map[string]any{
+			"verifyOperationContextValues": verifyModule.VerifyOperationContextValuesModule{
+				ResultsChan: resultsChan,
+			},
+		},
+	}
+	return resultsChan, cfg
+}

Then use it in each test:

-resultsChan := make(chan verifyModule.CapturedOperationValues, 1)
-cfg := config.Config{...}
+resultsChan, cfg := setupTestModule(t)

Also applies to: 94-94, 139-139

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 755cf67 and b827694.

📒 Files selected for processing (2)
  • router-tests/modules/verify-operation-context-values/module.go (1 hunks)
  • router-tests/modules/verify_operation_context_values_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
router-tests/modules/verify-operation-context-values/module.go (4)
router/core/modules.go (4)
  • ModuleContext (160-164)
  • Module (52-54)
  • ModuleInfo (44-50)
  • RouterMiddlewareHandler (102-105)
router/core/context.go (1)
  • RequestContext (60-136)
router/core/batch.go (1)
  • Handler (46-58)
router/internal/expr/expr.go (1)
  • Request (65-74)
⏰ 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). (10)
  • GitHub Check: build-router
  • GitHub Check: build_test
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: build_push_image
  • GitHub Check: integration_test (./telemetry)
  • GitHub Check: image_scan
  • GitHub Check: integration_test (./events)
  • GitHub Check: integration_test (./. ./fuzzquery ./lifecycle ./modules)
  • GitHub Check: build_test
🔇 Additional comments (7)
router-tests/modules/verify-operation-context-values/module.go (4)

13-23: Well-structured data capture struct.

The CapturedOperationValues struct effectively captures all necessary operation context values. The inclusion of both Variables as *astjson.Value and VariablesJSON as string provides flexibility for different testing scenarios.


31-37: Proper initialization with defensive programming.

The Provision method correctly initializes the logger and defensively creates the channel only if it's nil. This prevents overwriting an existing channel that might be configured externally.


52-58: Handle potential nil variables gracefully.

The nil check for captured.Variables and fallback to empty JSON object "{}" is appropriate for handling cases where no variables are provided in the GraphQL request.


60-64: Non-blocking channel send prevents deadlocks.

The use of select with a default case prevents the middleware from blocking when the channel is full. This is crucial for production scenarios where the test consumer might not be draining the channel.

router-tests/modules/verify_operation_context_values_test.go (3)

17-89: Comprehensive test coverage for operation context values.

The first test effectively verifies all major operation context values including the new Variables() method. The assertions cover operation name, type, hash, content, and variables in both parsed and JSON string formats.


91-134: Good coverage for edge case with empty variables.

The test properly verifies that the Variables() method returns a non-nil value even when no variables are provided, and correctly handles the empty variables scenario.


136-194: Thorough testing of mutation operations.

The mutation test effectively verifies that the operation context correctly identifies mutation operations and provides access to mutation variables with proper type handling (both integer and string variables).

Comment thread router-tests/modules/verify-operation-context-values/module.go
Comment thread router-tests/modules/verify-operation-context-values/module.go Outdated
Co-authored-by: Ludwig Bedacht <ludwig.bedacht@gmail.com>
@alepane21 alepane21 merged commit 1919009 into main Jul 15, 2025
31 of 32 checks passed
@alepane21 alepane21 deleted the ale/eng-7598-add-variables-to-requestcontextoperation branch July 15, 2025 09:11
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.

3 participants