Skip to content

Conversation

@ChiragAgg5k
Copy link
Member

@ChiragAgg5k ChiragAgg5k commented Jul 10, 2025

Summary by CodeRabbit

  • New Features

    • Added support for handling HTTP requests directly in the WebSocket server through a new event handler.
    • Introduced customizable HTTP endpoints, including /health for server status and /info for server metadata.
    • Enhanced both Swoole and Workerman adapters to allow registration of HTTP request callbacks.
  • Tests

    • Added test handlers for HTTP endpoints to verify server status and information responses.

@coderabbitai
Copy link

coderabbitai bot commented Jul 10, 2025

Walkthrough

A new onRequest method was introduced to the WebSocket server architecture, enabling HTTP request handling alongside WebSocket connections. This method was added to the abstract adapter, concrete Swoole and Workerman adapters, and the main server class. Example usage was implemented in both Swoole and Workerman test servers.

Changes

File(s) Change Summary
src/WebSocket/Adapter.php Added abstract onRequest(callable $callback): self method to the Adapter class.
src/WebSocket/Adapter/Swoole.php Implemented onRequest to register HTTP request callbacks via Swoole server's 'request' event; imported Swoole\Http\Response.
src/WebSocket/Adapter/Workerman.php Added private properties for message and request callbacks; implemented onRequest; modified onMessage to unify handling; added private setupMessageHandler method.
src/WebSocket/Server.php Added onRequest(callable $callback): self method to delegate HTTP request handling to the adapter with error management.
tests/servers/Swoole/server.php Registered an onRequest handler to serve /health and /info endpoints or return 404 for others; imported Swoole\Http\Response.
tests/servers/Workerman/server.php Registered an onRequest handler to serve /health and /info endpoints or return 404 for others; handles TCP connection and HTTP request.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Adapter
    participant HTTP Handler

    Client->>Server: HTTP request
    Server->>Adapter: onRequest(callback)
    Adapter->>HTTP Handler: Invoke callback with request/response
    HTTP Handler-->>Adapter: Processed response
    Adapter-->>Server: Return self
    Server-->>Client: HTTP response
Loading

Poem

A rabbit hops with nimble cheer,
Now WebSockets serve HTTP here!
With /health and /info endpoints bright,
Both Swoole and Workerman handle it right.
On every request, a callback’s in view—
Hooray for the code that now handles more than a few!
🐇✨


📜 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 74e9f1f and ecf1365.

📒 Files selected for processing (1)
  • tests/servers/Workerman/server.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/servers/Workerman/server.php
⏰ 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). (4)
  • GitHub Check: Unit & E2E (8.3)
  • GitHub Check: Unit & E2E (8.2)
  • GitHub Check: Unit & E2E (8.0)
  • GitHub Check: Unit & E2E (8.1)
✨ 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: 1

🧹 Nitpick comments (1)
tests/servers/Workerman/server.php (1)

46-68: Well-implemented HTTP request handler with proper endpoint structure.

The onRequest handler demonstrates excellent usage of the new HTTP request handling capability:

Strengths:

  • Proper HTTP response format with correct headers and status codes
  • Useful test endpoints (/health and /info) for monitoring
  • Clean path-based routing logic
  • Appropriate use of Connection: close header for stateless HTTP requests
  • Integration with WebSocket server's connection management via $server->getConnections()

The implementation correctly follows the adapter pattern and provides valuable functionality for testing and monitoring the WebSocket server.

Optional enhancement for robustness:

     ->onRequest(function (TcpConnection $connection, Request $request) use ($server) {
         echo 'HTTP request received: ', $request->path(), PHP_EOL;
 
+        try {
             if ($request->path() === '/health') {
                 $connection->send('HTTP/1.1 200 OK' . "\r\n" .
                                  'Content-Type: application/json' . "\r\n" .
                                  'Connection: close' . "\r\n\r\n" .
                                  json_encode(['status' => 'ok', 'message' => 'WebSocket server is running']));
             } elseif ($request->path() === '/info') {
                 $connection->send('HTTP/1.1 200 OK' . "\r\n" .
                                  'Content-Type: application/json' . "\r\n" .
                                  'Connection: close' . "\r\n\r\n" .
                                  json_encode([
                                      'server' => 'Workerman WebSocket',
                                      'connections' => count($server->getConnections()),
                                      'timestamp' => time()
                                  ]));
             } else {
                 $connection->send('HTTP/1.1 404 Not Found' . "\r\n" .
                                  'Connection: close' . "\r\n\r\n" .
                                  'Not Found');
             }
+        } catch (Throwable $e) {
+            echo 'Error handling HTTP request: ', $e->getMessage(), PHP_EOL;
+            $connection->send('HTTP/1.1 500 Internal Server Error' . "\r\n" .
+                             'Connection: close' . "\r\n\r\n" .
+                             'Internal Server Error');
+        }
     })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77004ba and bda4828.

📒 Files selected for processing (6)
  • src/WebSocket/Adapter.php (1 hunks)
  • src/WebSocket/Adapter/Swoole.php (2 hunks)
  • src/WebSocket/Adapter/Workerman.php (1 hunks)
  • src/WebSocket/Server.php (1 hunks)
  • tests/servers/Swoole/server.php (2 hunks)
  • tests/servers/Workerman/server.php (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
src/WebSocket/Adapter.php (3)
src/WebSocket/Server.php (1)
  • onRequest (204-215)
src/WebSocket/Adapter/Workerman.php (1)
  • onRequest (107-112)
src/WebSocket/Adapter/Swoole.php (1)
  • onRequest (129-136)
src/WebSocket/Server.php (3)
src/WebSocket/Adapter.php (1)
  • onRequest (90-90)
src/WebSocket/Adapter/Workerman.php (1)
  • onRequest (107-112)
src/WebSocket/Adapter/Swoole.php (1)
  • onRequest (129-136)
src/WebSocket/Adapter/Workerman.php (3)
src/WebSocket/Adapter.php (1)
  • onRequest (90-90)
src/WebSocket/Server.php (1)
  • onRequest (204-215)
src/WebSocket/Adapter/Swoole.php (1)
  • onRequest (129-136)
tests/servers/Workerman/server.php (3)
src/WebSocket/Adapter/Workerman.php (4)
  • Workerman (9-140)
  • onRequest (107-112)
  • send (41-46)
  • getConnections (136-139)
src/WebSocket/Adapter.php (3)
  • onRequest (90-90)
  • send (40-40)
  • getConnections (131-131)
src/WebSocket/Server.php (3)
  • onRequest (204-215)
  • send (62-71)
  • getConnections (222-225)
⏰ 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). (4)
  • GitHub Check: Unit & E2E (8.0)
  • GitHub Check: Unit & E2E (8.2)
  • GitHub Check: Unit & E2E (8.3)
  • GitHub Check: Unit & E2E (8.1)
🔇 Additional comments (7)
src/WebSocket/Adapter.php (1)

85-90: LGTM! Abstract method follows established patterns.

The abstract onRequest method declaration is consistent with other event handler methods in the class and properly defines the interface contract for concrete adapters.

src/WebSocket/Adapter/Swoole.php (2)

6-6: LGTM! Import needed for Response type hints.

The Swoole\Http\Response import is required for the new onRequest method implementation.


129-136: LGTM! Implementation follows Swoole patterns.

The onRequest method implementation is consistent with Swoole's event handling pattern and other methods in the class. The callback wrapper properly provides Request and Response objects to the user callback.

src/WebSocket/Server.php (1)

199-215: LGTM! Consistent with existing event handler pattern.

The onRequest method implementation follows the exact same pattern as other event handler methods in the class with proper error handling and method chaining.

tests/servers/Swoole/server.php (2)

6-6: LGTM! Import needed for Response type hints.

The Swoole\Http\Response import is required for the new HTTP request handler.


46-65: LGTM! Excellent example of HTTP request handling.

The HTTP request handler provides good examples of different response scenarios and nicely integrates with the WebSocket server by showing connection counts in the /info endpoint.

tests/servers/Workerman/server.php (1)

6-7: LGTM! Required imports for HTTP request handling.

The new imports are necessary for the onRequest handler implementation and follow the correct Workerman namespace conventions.

@ChiragAgg5k ChiragAgg5k requested a review from Copilot July 10, 2025 11:08
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: 1

♻️ Duplicate comments (1)
src/WebSocket/Adapter/Workerman.php (1)

111-117: Signature inconsistency issue remains unresolved.

The callback signature inconsistency identified in the previous review still exists. The Workerman adapter calls the callback with (TcpConnection, Request) while the Swoole adapter uses (Request, Response). This breaks the abstraction and makes it difficult to write adapter-agnostic code.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bda4828 and 74e9f1f.

📒 Files selected for processing (2)
  • src/WebSocket/Adapter/Workerman.php (4 hunks)
  • tests/servers/Workerman/server.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/servers/Workerman/server.php
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/WebSocket/Adapter/Workerman.php (3)
src/WebSocket/Adapter.php (2)
  • onRequest (90-90)
  • onMessage (83-83)
src/WebSocket/Server.php (2)
  • onRequest (204-215)
  • onMessage (168-179)
src/WebSocket/Adapter/Swoole.php (2)
  • onRequest (129-136)
  • onMessage (109-116)
🔇 Additional comments (3)
src/WebSocket/Adapter/Workerman.php (3)

8-8: Import looks good.

The addition of the HTTP Request import is appropriate for the new HTTP request handling functionality.


20-23: Good encapsulation of callback storage.

The new private properties properly encapsulate the callback storage, following good OOP principles.


96-97: Consistent refactoring pattern.

The modification to store the callback and delegate to setupMessageHandler() maintains consistency with the new unified message handling approach.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Adds HTTP request handling to the WebSocket server API and adapters, and updates test servers to support /health and /info endpoints.

  • Introduce onRequest method in Server and Adapter interface
  • Implement HTTP request routing in both Workerman and Swoole adapters
  • Update test server scripts to verify new HTTP endpoints

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/servers/Workerman/server.php Add HTTP /health and /info handlers in Workerman
tests/servers/Swoole/server.php Add HTTP /health and /info handlers in Swoole
src/WebSocket/Server.php Add onRequest to server API and error handling
src/WebSocket/Adapter.php Extend interface with abstract onRequest
src/WebSocket/Adapter/Workerman.php Implement onRequest and unify handler setup
src/WebSocket/Adapter/Swoole.php Implement onRequest for Swoole adapter
Comments suppressed due to low confidence (1)

src/WebSocket/Server.php:208

  • The catch (Throwable $error) reference isn’t fully qualified or imported in this namespace. Use catch (\Throwable $error) or add use Throwable; at the top to avoid a runtime error.
        } catch (Throwable $error) {

@christyjacob4 christyjacob4 merged commit bc82978 into main Jul 15, 2025
7 checks passed
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.

5 participants