Skip to content

Conversation

thienvu18
Copy link

@thienvu18 thienvu18 commented Jul 16, 2025

Description

This PR adds support for gRPC Server Interceptors to the Laravel Bridge package, providing powerful middleware-like functionality for gRPC services.

Features Added:

  1. Server Interceptor Interface: Added GrpcServerInterceptorInterface for implementing custom interceptors

    • Method signature: intercept(string $method, ContextInterface $context, string $body, callable $next)
    • Enables pre and post-processing of gRPC requests
  2. Global Interceptors Support:

    • Configure interceptors that apply to all gRPC services
    • Set via 'interceptors' array in grpc configuration
    • Executed in the order they are defined
  3. Service-Specific Interceptors:

    • Configure interceptors for individual services
    • Allows fine-grained control over which interceptors apply to which services
    • Combined with global interceptors for comprehensive request handling
  4. Comprehensive Documentation:

    • Added clear examples of interceptor implementation
    • Documented both global and service-specific configuration patterns

Use Cases:

  • Request/response logging and monitoring
  • Authentication and authorization
  • Input validation
  • Response caching
  • Rate limiting
  • Error handling and transformation
  • Performance monitoring

This enhancement brings Laravel-style middleware concepts to gRPC services, making it easier to implement cross-cutting concerns in a clean and reusable way.

Fixes # (issue)

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I wrote unit tests for my code (if tests is required for my changes)
  • I have made changes in CHANGELOG.md file

Summary by CodeRabbit

  • New Features

    • Added support for gRPC server interceptors, enabling custom logic before or after gRPC service calls.
    • Interceptors can be registered globally or per service through configuration settings.
  • Documentation

    • Enhanced documentation with examples on creating and configuring gRPC interceptors, including global and per-service registration guidance.

@thienvu18 thienvu18 requested a review from butschster as a code owner July 16, 2025 08:41
Copy link

coderabbitai bot commented Jul 16, 2025

Walkthrough

Support for gRPC server interceptors has been added to the Laravel RoadRunner Bridge. This includes a new interface for interceptors, updates to service registration and invocation logic to apply interceptors globally or per service, and expanded documentation and configuration examples illustrating their usage.

Changes

File(s) Change Summary
README.md Documentation updated to explain gRPC interceptors, with usage examples and configuration guidance.
config/roadrunner.php Commented examples added for configuring global and per-service interceptors in gRPC section.
src/Grpc/GrpcServerInterceptorInterface.php New interface for gRPC server interceptors introduced.
src/Grpc/GrpcWorker.php Logic updated to register services with global and/or per-service interceptors.
src/Grpc/Server.php Service registration and invocation updated to support interceptor pipelines; method signatures changed.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Interceptor1
    participant Interceptor2
    participant Service

    Client->>Server: gRPC request (method, context, body)
    Server->>Interceptor1: intercept(method, context, body, next)
    Interceptor1->>Interceptor2: intercept(method, context, body, next)
    Interceptor2->>Service: invoke(method, context, body)
    Service-->>Interceptor2: response
    Interceptor2-->>Interceptor1: response
    Interceptor1-->>Server: response
    Server-->>Client: response
Loading

Suggested labels

type:enhancement

Suggested reviewers

  • butschster
  • roxblnfk

Poem

In the land of gRPC hops,
Interceptors now make their stops.
With logging and checks, they leap in between,
Ensuring each service is tidy and clean.
From docs to config, the changes are neat—
A rabbit’s code, now more complete! 🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 PHPStan (2.1.17)

Note: Using configuration file /phpstan.neon.dist.
Path /fixes does not exist


📜 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 9241e96 and 6f6543f.

📒 Files selected for processing (2)
  • src/Grpc/GrpcWorker.php (1 hunks)
  • src/Grpc/Server.php (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/Grpc/GrpcWorker.php
  • src/Grpc/Server.php
✨ 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.

Copy link

@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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47c04da and 9241e96.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • config/roadrunner.php (1 hunks)
  • src/Grpc/GrpcServerInterceptorInterface.php (1 hunks)
  • src/Grpc/GrpcWorker.php (1 hunks)
  • src/Grpc/Server.php (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/Grpc/GrpcWorker.php (1)
src/Grpc/Server.php (1)
  • registerService (68-74)
src/Grpc/Server.php (1)
src/Grpc/GrpcServerInterceptorInterface.php (1)
  • intercept (11-11)
🔇 Additional comments (8)
config/roadrunner.php (2)

21-28: LGTM! Clear example of service-specific interceptors configuration.

The example effectively demonstrates how to configure interceptors for individual services.


29-32: LGTM! Global interceptors configuration is well-placed.

The configuration properly supports global interceptors that apply to all gRPC services.

src/Grpc/GrpcWorker.php (2)

35-36: LGTM! Global interceptors retrieval is correct.

The code properly retrieves global interceptors from configuration with a safe default value.


46-46: LGTM! Service registration properly includes interceptors.

The code correctly passes the merged interceptors to the server's registerService method.

README.md (2)

223-248: LGTM! Clear interceptor documentation and example.

The example effectively demonstrates how to implement a gRPC server interceptor with pre and post-processing logic.


250-278: LGTM! Comprehensive interceptor configuration examples.

The documentation clearly explains both global and service-specific interceptor configuration patterns.

src/Grpc/Server.php (2)

40-42: LGTM! Interceptors property properly typed and structured.

The property follows the existing pattern for storing service-specific data.


145-153: LGTM! Parameter rename improves clarity.

The rename from $service to $serviceName better reflects the parameter's purpose.


interface GrpcServerInterceptorInterface
{
public function intercept(string $method, ContextInterface $context, string $body, callable $next);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add return type annotation to the intercept method.

The intercept method should declare its return type for better type safety and IDE support.

Apply this diff to add the return type:

-    public function intercept(string $method, ContextInterface $context, string $body, callable $next);
+    public function intercept(string $method, ContextInterface $context, string $body, callable $next): string;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public function intercept(string $method, ContextInterface $context, string $body, callable $next);
public function intercept(string $method, ContextInterface $context, string $body, callable $next): string;
🤖 Prompt for AI Agents
In src/Grpc/GrpcServerInterceptorInterface.php at line 11, the intercept method
lacks a return type declaration. Add the appropriate return type annotation to
the method signature to improve type safety and IDE support. Determine the
correct return type based on the method's expected output and append it after
the parameter list.

Comment on lines 155 to 168
$service = $this->services[$serviceName] ?? [];
$interceptors = $this->interceptors[$serviceName] ?? [];

$handler = function ($method, $context, $body) use ($service) {
return $service->invoke($method, $context, $body);
};

$pipeline = array_reduce(
array_reverse($interceptors),
fn($next, $interceptor) => fn($method, $context, $body) => (new $interceptor)->intercept($method, $context, $body, $next),
$handler
);

return $pipeline($method, $context, $body);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Remove redundant assignment and optimize interceptor instantiation.

The code has redundancy and performance issues:

  1. Line 155 assigns service with a fallback even though we already verified it exists.
  2. Interceptors are instantiated on every request, which is inefficient.

Apply this diff to fix the issues:

-        $service = $this->services[$serviceName] ?? [];
+        $service = $this->services[$serviceName];
         $interceptors = $this->interceptors[$serviceName] ?? [];

         $handler = function ($method, $context, $body) use ($service) {
             return $service->invoke($method, $context, $body);
         };

         $pipeline = array_reduce(
             array_reverse($interceptors),
-            fn($next, $interceptor) => fn($method, $context, $body) => (new $interceptor)->intercept($method, $context, $body, $next),
+            fn($next, $interceptor) => function($method, $context, $body) use ($interceptor, $next) {
+                // Consider caching interceptor instances in registerService method
+                return $this->worker->application()->make($interceptor)->intercept($method, $context, $body, $next);
+            },
             $handler
         );

This uses the Laravel container to instantiate interceptors, which allows for dependency injection and potential singleton behavior.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$service = $this->services[$serviceName] ?? [];
$interceptors = $this->interceptors[$serviceName] ?? [];
$handler = function ($method, $context, $body) use ($service) {
return $service->invoke($method, $context, $body);
};
$pipeline = array_reduce(
array_reverse($interceptors),
fn($next, $interceptor) => fn($method, $context, $body) => (new $interceptor)->intercept($method, $context, $body, $next),
$handler
);
return $pipeline($method, $context, $body);
$service = $this->services[$serviceName];
$interceptors = $this->interceptors[$serviceName] ?? [];
$handler = function ($method, $context, $body) use ($service) {
return $service->invoke($method, $context, $body);
};
$pipeline = array_reduce(
array_reverse($interceptors),
fn($next, $interceptor) => function($method, $context, $body) use ($interceptor, $next) {
// Consider caching interceptor instances in registerService method
return $this->worker->application()->make($interceptor)
->intercept($method, $context, $body, $next);
},
$handler
);
return $pipeline($method, $context, $body);
🤖 Prompt for AI Agents
In src/Grpc/Server.php around lines 155 to 168, remove the redundant fallback
assignment for $service since its existence is already verified. Refactor the
interceptor instantiation inside the array_reduce to instantiate each
interceptor only once before the pipeline creation, using the Laravel container
to resolve them for better performance and dependency injection support. Replace
the inline new interceptor instantiation with container-based resolution outside
the pipeline function to avoid creating interceptors on every request.

@roxblnfk
Copy link
Member

roxblnfk commented Jul 17, 2025

What about using the same spiral/interceptors like in gRPC client?

We can run it like in the Spiral RoadRunner Bridge:
https://github.com/spiral/roadrunner-bridge/blob/005e5a0ce21b9face0e767f2f3d6b1ad0d1643a0/src/GRPC/Internal/Invoker.php#L40-L45

@thienvu18
Copy link
Author

I come from Laravel and I am new to Spiral. Right now, I just implement interceptors like Laravel middlewares, but of course I don't want to remake something that Spiral already has. You told me that Spiral offers an Interceptor interface, which sounds great, but I don't really know how to use it. Could you please share a simple example or explain how it works? Also, what benefits does it have compared to my current approach? Thank you!

@roxblnfk
Copy link
Member

A common interface allows to use the same interceptor implementations in many places. Additionally, the code is tested and production ready.
By the way, Spiral Interceptors were already added along with the gRPC Client in #152.

Documentation is here: https://spiral.dev/docs/framework-interceptors

@butschster butschster requested a review from roxblnfk July 22, 2025 11:09
@butschster butschster self-assigned this Jul 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants