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

Flare Daemon Laravel Package

spatie/flare-daemon

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Developers

  1. Install via Composer (automatically included with spatie/laravel-flare or spatie/flare-client):

    composer require spatie/flare-daemon
    

    The daemon binary (vendor/bin/flare-daemon) is now available.

  2. Start the Daemon Locally (default: 127.0.0.1:8787):

    php vendor/bin/flare-daemon
    

    For debugging, add --verbose:

    php vendor/bin/flare-daemon --verbose
    
  3. Configure Flare Client (Laravel): In config/flare.php, set:

    'transport' => [
        'daemon' => [
            'enabled' => true,
            'url' => 'http://127.0.0.1:8787',
        ],
    ],
    

    Or via environment variables:

    FLARE_TRANSPORT=daemon
    FLARE_DAEMON_URL=http://127.0.0.1:8787
    
  4. Test Integration: Trigger an error in your Laravel app (e.g., abort(500)). Verify the daemon forwards it to Flare by:

    • Checking the daemon logs (DEBUG level with --verbose).
    • Monitoring Flare’s Live Tail for the error.

First Use Case: Debugging a Production Issue

  1. Reproduce Locally:

    • Start the daemon in verbose mode:
      php vendor/bin/flare-daemon --verbose &
      
    • Simulate a production error (e.g., throw new \Exception('Test error')).
    • Observe the daemon’s real-time logs to confirm payload buffering/flushing.
  2. Verify Async Behavior:

    • Use curl to send a test payload directly to the daemon:
      curl -X POST http://127.0.0.1:8787/v1/errors -d '{"api_key":"YOUR_KEY","payload":"test"}'
      
    • Check Flare’s Live Tail to confirm async delivery.
  3. Fallback Testing:

    • Stop the daemon (Ctrl+C).
    • Trigger another error. Flare should fall back to direct delivery (visible in Flare’s Settings > Transport).

Implementation Patterns

Workflow: Integrating into Laravel CI/CD

  1. Local Development:

    • Run the daemon as a background process (e.g., via laravel-valet or docker-compose).
    • Use --verbose to debug payloads during feature development.
  2. Staging/Production:

    • Docker Deployment:
      # docker-compose.yml
      services:
        flare-daemon:
          image: ghcr.io/spatie/flare-daemon
          ports:
            - "8787:8787"
          environment:
            - FLARE_DAEMON_LISTEN=0.0.0.0:8787
            - PHP_MEMORY_LIMIT=256M
      
    • Kubernetes (Helm):
      helm install flare-daemon oci://ghcr.io/spatie/charts/flare-daemon \
        --set phpMemoryLimit=256M \
        --namespace monitoring
      
      Configure Laravel’s FLARE_DAEMON_URL to point to the Kubernetes service:
      FLARE_DAEMON_URL=http://flare-daemon.monitoring.svc.cluster.local:8787
      
  3. Graceful Shutdowns:

    • Deployments: Use the composer.lock watcher to auto-shutdown during composer install:
      php vendor/bin/flare-daemon --composer-lock=/path/to/composer.lock
      
    • Docker: Add a health check to restart the daemon on failure:
      healthcheck:
        test: ["CMD", "curl", "-f", "http://localhost:8787/health"]
        interval: 30s
        timeout: 10s
        retries: 3
      

Pattern: Buffer Management

  1. Tune Buffer Thresholds (via env vars):

    FLARE_DAEMON_BUFFER_BYTES=524288    # 512 KB (default: 256 KB)
    FLARE_DAEMON_FLUSH_AFTER_SECONDS=5  # Flush every 5s (default: 10s)
    
    • Use Case: Reduce FLUSH_AFTER_SECONDS for low-latency requirements (e.g., financial apps).
    • Tradeoff: Smaller buffers = more frequent upstream requests (higher Flare API calls).
  2. Quota Handling:

    • The daemon auto-pauses ingestion if Flare returns 429 (rate-limited).
    • Monitor quota state via /status endpoint (e.g., for alerting):
      curl http://127.0.0.1:8787/status
      
      Example response:
      {
        "buffers": {
          "api_key_123": {
            "errors": {"count": 42, "bytes": 10240},
            "traces": {"count": 0, "bytes": 0}
          }
        },
        "quota_paused": false
      }
      

Pattern: Testing and Validation

  1. Unit Testing:

    • Mock the daemon’s HTTP server in PHPUnit:
      use Spatie\FlareDaemon\Daemon;
      use React\Socket\ConnectionInterface;
      
      $daemon = new Daemon();
      $daemon->getHttpServer()->on('request', function (ConnectionInterface $conn) {
          // Assert payload structure
          $payload = json_decode($conn->getResource()->getData(), true);
          $this->assertArrayHasKey('api_key', $payload);
      });
      
  2. Integration Testing:

    • Use the test.sh script to validate end-to-end flow:
      bash vendor/spatie/flare-daemon/tests/test.sh YOUR_API_KEY
      
    • For Laravel, extend the script to include:
      php artisan flare:report --force  # Trigger a test error
      
  3. Load Testing:

    • Simulate high traffic with k6:
      k6 run vendor/spatie/flare-daemon/loadtest/loadtest.js
      
    • Goal: Ensure the daemon handles your app’s peak error rate (e.g., 10K errors/sec).

Pattern: Extending Functionality

  1. Custom Payload Validation:

    • Override the Ingest middleware in a service provider:
      use Spatie\FlareDaemon\Ingest\IngestMiddleware;
      
      $daemon->getIngestMiddleware()->addValidator(function ($payload) {
          if (!array_key_exists('custom_field', $payload)) {
              throw new \RuntimeException('Missing custom_field');
          }
      });
      
  2. Add a Health Endpoint:

    • Extend the daemon’s routes:
      $daemon->getHttpServer()->on('request', function ($request) {
          if ($request->getPath() === '/custom-health') {
              return new React\Http\Message\Response(200, [], 'OK');
          }
      });
      
  3. Log Buffer Metrics:

    • Use the status endpoint to build a custom Prometheus exporter:
      $status = json_decode(file_get_contents('http://127.0.0.1:8787/status'), true);
      $metrics = [
          'flare_daemon_buffer_errors_total' => $status['buffers']['api_key_123']['errors']['count'],
      ];
      

Gotchas and Tips

Pitfalls

  1. Buffer Memory Leaks:

    • Issue: In-memory buffers grow indefinitely if the daemon crashes or Flare is unreachable.
    • Fix: Set FLARE_DAEMON_BUFFER_BYTES to a conservative limit (e.g., 1M) for high-traffic apps.
    • Workaround: Use the composer.lock watcher to restart the daemon on deployments.
  2. Quota Throttling:

    • Issue: The daemon pauses ingestion on 429 responses, which may delay critical errors.
    • Fix: Monitor /status and adjust Flare API keys’ quotas in Flare Settings > API Keys.
    • Tip: Use multiple API keys (e.g., errors, logs) to distribute load.
  3. Docker Networking:

    • Issue: Daemon unreachable from Laravel containers if not on the same network.
    • Fix: Use Docker’s host network or a custom bridge:
      networks:
        default:
          name: lar
      
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