Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Websocket Laravel Package

phrity/websocket

PHP WebSocket client and multi-connection server with ws/wss support. Includes listener callbacks, standard Close and Ping/Pong handling, optional deflate compression, fragmentation and masking support, plus middleware system for extending behavior.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Modular Design: The package’s middleware-based architecture remains unchanged, maintaining alignment with Laravel’s dependency injection and service container patterns. The new release reinforces this by fixing a critical edge case (Detach connection on failed handshake), reducing implicit state leaks.
    • Dual Client/Server Support: Still ideal for Laravel’s real-time needs (e.g., chat, live updates), with the fix mitigating a potential memory leak during handshake failures—a common pain point in persistent connections.
    • Protocol Compliance: RFC 6455 adherence is preserved, and the fix ensures connections are properly cleaned up, reducing protocol violations during handshake errors.
    • Extensibility: Custom middlewares remain viable, but the fix simplifies error handling (e.g., no orphaned connections during auth failures).
    • Compression Support: Unchanged, but the handshake fix reduces bandwidth waste from failed connections.
  • Cons:

    • No Laravel-Specific Integrations: Still requires manual bridging (e.g., no native Laravel Echo/Pusher support). The fix doesn’t address this but reduces friction for custom integrations.
    • Blocking I/O: The receive() method remains blocking. The handshake fix doesn’t resolve this, but it mitigates one source of connection leaks.
    • State Management: Connection detachment on failure improves state management, but Laravel’s stateless HTTP model still clashes with WebSocket persistence. The fix reduces but doesn’t eliminate this risk.

Integration Feasibility

  • Laravel Stack Fit:

    • Client: The handshake fix improves reliability for Laravel’s HTTP client integrations (e.g., Guzzle). Failed connections will now detach cleanly, reducing resource leaks in queue workers.
    • Server: The fix is critical for Laravel-based WebSocket servers, preventing memory bloat from failed handshakes (e.g., during auth middleware execution).
    • Middleware: The update aligns with Laravel’s middleware termination patterns, making it easier to integrate with existing auth/validation stacks.
  • Dependencies:

    • No changes to core dependencies (ext-sockets, ext-zlib). The fix is self-contained and doesn’t introduce conflicts with Laravel’s async libraries.

Technical Risk

  • Blocking Operations: Unchanged risk. Mitigation strategies (e.g., queue jobs) remain necessary.
  • Connection Management: Reduced risk. The fix prevents orphaned connections during handshake failures, but Laravel’s stateless model still requires external management (e.g., Redis-backed connection tracking).
  • Middleware Complexity: Lowered risk. The fix ensures failed handshakes don’t leave middleware stacks in inconsistent states, simplifying custom middleware testing.
  • Security: No auth changes, but the fix reduces attack surface by cleaning up failed connections (e.g., brute-force attempts).
  • Scaling: The fix improves resource efficiency under high failure rates (e.g., load testing), but single-threaded scaling remains a bottleneck.

Key Questions

  1. Use Case Clarity: Unchanged.
  2. Async Requirements: Unchanged.
  3. State Management:
    • Updated: How will the package’s new connection detachment behavior interact with Laravel’s session/connection management (e.g., will failed WebSocket handshakes trigger Laravel events or require custom listeners)?
  4. Security Model: Unchanged.
  5. Scaling Strategy: Unchanged.
  6. Monitoring/Observability:
    • Updated: How will the new handshake failure metric (detached connections) be logged? Should Prometheus counters be added for failed handshakes?
  7. Fallback Mechanisms: Unchanged.

Integration Approach

Stack Fit

  • Laravel Client Integration:

    • Updated: The fix reduces risk for queue-based clients. Example:
      // app/Jobs/SendWebSocketMessage.php
      class SendWebSocketMessage implements ShouldQueue {
          public function handle() {
              $client = new WebSocket\Client("wss://example.com");
              try {
                  $client->text($this->message)->start(); // Handshake failures now detach cleanly
              } catch (ConnectionException $e) {
                  Log::error("WebSocket handshake failed: " . $e->getMessage());
              }
          }
      }
      
    • Async libraries (e.g., ReactPHP) are still recommended for high-throughput scenarios.
  • Laravel Server Integration:

    • Updated: The fix simplifies error handling in custom servers. Example:
      // app/Services/WebSocketServerService.php
      class WebSocketServerService {
          public function start() {
              $server = new WebSocket\Server();
              $server->onOpen(function ($connection) {
                  // Handshake is now guaranteed to succeed or detach
                  Auth::validateOrReject($connection->getMeta('handshake.headers'));
              });
              $server->start();
          }
      }
      
    • Hybrid approaches (e.g., mixing with beyondcode/laravel-websockets) benefit from reduced connection leaks.
  • Middleware Integration:

    • Updated: Custom middleware can now safely assume failed handshakes won’t leave connections in limbo. Example:
      // app/Http/Middleware/ValidateWebSocketToken.php
      class ValidateWebSocketToken {
          public function __invoke($request, $next) {
              if (!$request->hasWebSocketToken()) {
                  $request->connection->close(4001, 'Invalid token'); // Detaches cleanly
                  return;
              }
              return $next($request);
          }
      }
      

Migration Path

  1. Pilot Phase:
    • Updated: Prioritize features with high handshake failure rates (e.g., auth-heavy endpoints) to validate the fix’s impact on connection stability.
  2. Server Pilot:
    • Updated: Monitor detached connection metrics to tune auth middleware (e.g., rate-limiting).
  3. Full Integration:
    • Updated: Add logging for ConnectionException events to audit handshake failures during migration.
  4. Fallback Strategy: Unchanged.

Compatibility

  • Laravel 8/9/10: The fix is backward-compatible. No changes to the package’s API surface.
  • PHP 8.1+: The update doesn’t introduce breaking changes for PHP 8.1+ features (e.g., typed properties).
  • Existing Middlewares: All existing middlewares (e.g., PingResponder) remain compatible, but their error handling may now rely on detached connections.

Operational Impact

Maintenance

  • Reduced: Fewer edge cases to debug (e.g., no more "zombie connections" after failed handshakes). The fix lowers maintenance overhead for connection-heavy applications.
  • Logging: Add logging for ConnectionException to track handshake failures:
    $server->onError(function ($server, $connection, $code, $message) {
        Log::warning("WebSocket error [$code]: $message");
    });
    

Support

  • Improved: Support tickets related to connection leaks during handshakes should decrease. Document the new behavior for developers:

    "Failed handshakes now detach connections immediately. Custom middleware must handle ConnectionException for graceful fallbacks."

Scaling

  • Improved: Reduced memory bloat from failed connections improves scalability under high load (e.g., DDoS scenarios). Example:
    # Monitor detached connections in Laravel Tinker
    $server->getConnections()->filter(fn($conn) => $conn->isDetached())->count();
    

Failure Modes

  • Mitigated:
    • Handshake Failures: No longer leave connections in inconsistent states.
    • Resource Leaks: Detached connections free up file descriptors/sockets.
  • New Risks:
    • Over-Detachment: Aggressive middleware (e.g., strict auth) may detach legitimate connections. Mitigate with:
      $server->onError(function ($server, $connection, $code) {
          if ($code === 1002) { // Protocol error (e.g., malformed frame)
              $connection->close(1008, 'Policy violation');
          }
      });
      

Ramp-Up

  • Training: Highlight the fix in onboarding for teams using custom WebSocket logic:

    "Connections now detach on handshake failures. Test your middleware’s error paths with the new behavior."

  • Testing: Add integration tests for failed handshakes:
    public function testFailedHandshakeDetachesConnection() {
        $server = new WebSocket\Server();
        $server->onOpen(function () { throw new Exception('Auth failed'); });
        $server->start();
        $this->assertCount(0, $server->getConnections()); // No orphaned connections
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony