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

Sse Laravel Package

hosmelq/sse

WHATWG-compliant PHP 8.2+ client for consuming Server-Sent Events. Connect via GET/POST using Guzzle, iterate events with a memory-efficient generator, and access data/event/id/retry fields with optional JSON decoding.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Real-Time Data Consumption: Ideal for Laravel applications requiring server-pushed updates (e.g., live notifications, stock tickers, or collaborative tools). Complements Laravel’s event system but focuses on WHATWG-compliant SSE consumption rather than emission.
  • Memory Efficiency: Generator-based event iteration avoids loading entire streams into memory, critical for Laravel’s long-running processes (e.g., queues, cron jobs, or background tasks).
  • Protocol Compliance: WHATWG compliance ensures seamless integration with modern browsers and other SSE-compliant services (e.g., third-party APIs or Laravel’s own SSE endpoints).
  • Decoupled Architecture: Enables event-driven workflows where Laravel services react to external SSE streams without tight coupling.

Integration Feasibility

  • Laravel Ecosystem Synergy:
    • HTTP Client Compatibility: Works natively with Laravel’s Http client or Guzzle, requiring minimal configuration.
    • Event System Integration: SSE events can trigger Laravel’s Event facade, enabling cross-platform consistency (e.g., broadcasting to Pusher or WebSocket clients).
    • Queue Integration: Perfect for async processing (e.g., dispatching jobs per SSE event) via Laravel’s queue system.
  • Dependency Lightweight: Only requires PHP 8.2+ and Guzzle (or Laravel’s HTTP client), avoiding heavy infrastructure changes.
  • Artisan/Console Support: SSE consumption can be encapsulated in Laravel Artisan commands or queue workers, fitting Laravel’s CLI-driven workflows.

Technical Risk

  • Connection Persistence: SSE streams are long-lived connections, which may conflict with Laravel’s request lifecycle (e.g., middleware, routing). Mitigation:
    • Use Artisan commands or queue workers for background consumption.
    • Customize Guzzle’s connection pooling for persistent streams.
  • Error Handling: SSE streams can fail due to network issues or protocol violations. The package’s exception hierarchy (SSEConnectionException, SSEProtocolException) must be mapped to Laravel’s logging (Log::error) and retry mechanisms (e.g., Laravel\Queue\Retryable).
  • State Management: Last-Event-ID is critical for reconnecting to streams. Laravel’s session/cookie system may not persist this state; alternatives:
    • Database-backed storage (e.g., Cache::remember or a dedicated table).
    • Redis for distributed environments.
  • Authentication: SSE endpoints may require auth (e.g., tokens). Laravel’s Http client supports headers, but persistent auth may need custom interceptors.

Key Questions

  1. Use Case Clarity:
    • Is SSE consumption for server-side processing (e.g., background jobs) or client-side delivery (e.g., frontend JS)?
    • Will events trigger Laravel actions (e.g., jobs, notifications) or be processed synchronously?
  2. Scaling Requirements:
    • How many concurrent SSE connections are needed? (Guzzle’s default connection pooling may require tuning.)
    • Will events be fan-out (e.g., broadcast to multiple services) or point-to-point?
  3. Observability:
    • How will event processing metrics (e.g., latency, errors) be monitored? (Integrate with Laravel Scout or custom Prometheus metrics.)
  4. Security:
    • Are SSE endpoints authenticated? (Laravel’s HTTP client supports tokens/headers, but persistent auth may need a custom interceptor.)
    • How will connection timeouts/retry logic be handled? (Default Guzzle timeouts may conflict with SSE’s long-lived nature.)
  5. Failure Modes:
    • What’s the recovery strategy for failed connections? (e.g., exponential backoff, circuit breakers).
    • How will partial event data (e.g., malformed JSON) be handled?

Integration Approach

Stack Fit

  • Laravel HTTP Client: Prefer Laravel’s native Http client for consistency:
    use Illuminate\Support\Facades\Http;
    $client = new \HosmelQ\SSE\Client(Http::client());
    
  • Queue Integration: For async processing, wrap the SSE consumer in a ShouldQueue job:
    class ProcessSSEEvents implements ShouldQueue
    {
        public function handle() {
            $client = new \HosmelQ\SSE\Client();
            foreach ($client->get('https://api.example.com/stream')->events() as $event) {
                // Dispatch Laravel events or process data
                ProcessEvent::dispatch($event);
            }
        }
    }
    
  • Event Bridge: Use Laravel’s Event facade to normalize SSE events:
    foreach ($eventSource->events() as $event) {
        event(new SSEEvent($event->data, $event->event));
    }
    
  • Service Container: Register the Client in Laravel’s DI container for testability:
    $this->app->bind(\HosmelQ\SSE\Client::class, fn () => new \HosmelQ\SSE\Client());
    

Migration Path

  1. Phase 1: Proof of Concept
    • Test with a single SSE endpoint in an Artisan command or tinker:
      php artisan make:command ProcessSSEEvents
      
    • Validate event parsing, error handling, and Laravel integration (e.g., logging, jobs).
    • Example command:
      public function handle() {
          $client = new \HosmelQ\SSE\Client();
          $eventSource = $client->get('https://api.example.com/stream');
          foreach ($eventSource->events() as $event) {
              Log::info("Received event: {$event->data}");
          }
      }
      
  2. Phase 2: Queue-Based Scaling
    • Move consumption to a queue worker (e.g., ProcessSSEEvents::dispatch()).
    • Implement Last-Event-ID persistence (e.g., Redis or DB) for reconnection:
      $lastEventId = Cache::get('sse_last_event_id', null);
      $eventSource = $client->get('https://api.example.com/stream', [
          'headers' => ['Last-Event-ID' => $lastEventId]
      ]);
      
  3. Phase 3: Observability
    • Add metrics (e.g., Laravel Debugbar or Prometheus):
      foreach ($eventSource->events() as $event) {
          $start = microtime(true);
          // Process event
          $duration = microtime(true) - $start;
          Metrics::record('sse.event_processing', $duration);
      }
      
    • Set up alerts for connection drops (e.g., Laravel Horizon for queue monitoring).

Compatibility

  • Laravel Versions: Tested on PHP 8.2+; ensure compatibility with Laravel 10/11 (no breaking changes expected).
  • HTTP Middleware: Apply Laravel middleware to the Http client:
    $client = new \HosmelQ\SSE\Client(Http::withOptions([
        'headers' => ['Authorization' => 'Bearer ' . auth()->token()]
    ])->client());
    
  • CORS/CSRF: Not applicable for server-side consumption, but client-side SSE endpoints must handle CORS if exposed.

Sequencing

  1. Dependency Injection: Bind the Client to Laravel’s container for easy mocking in tests.
  2. Event Listeners: Attach listeners to SSE-triggered events:
    Event::listen(SSEEvent::class, function ($event) {
        Notification::send(User::all(), new SSEUpdate($event->data));
    });
    
  3. Graceful Shutdown: Handle SSEConnectionException to close connections cleanly:
    try {
        foreach ($eventSource->events() as $event) { ... }
    } catch (SSEConnectionException $e) {
        Log::error("SSE connection failed: " . $e->getMessage());
        Cache::put('sse_last_event_id', $eventSource->getLastEventId(), now()->addHour());
    }
    
  4. Testing: Write feature tests for SSE consumption:
    public function test_sse_consumption() {
        $this->artisan('ProcessSSEEvents')
             ->expectsOutput('Received event: {"data": "test"}')
             ->assertExitCode(0);
    }
    

Operational Impact

Maintenance

  • Library Updates: Monitor hosmelq/sse for updates (MIT license allows forks if needed). Subscribe to release notes or set up a GitHub watch.
  • Dependency Management: Pin the package version in composer.json to avoid unexpected breaking changes:
    "require": {
        "hosmelq/sse": "^0.1.0"
    }
    
  • Custom Extensions: Plan for potential extensions (e.g., custom reconnection logic, auth middleware) by:
    • Creating a wrapper class around \HosmelQ\SSE\Client.
    • Using Laravel’s service provider to bind extended functionality.

Support

  • Debugging: Leverage the package’s exception hierarchy for targeted debugging
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope