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

Trace Replay Laravel Package

iazaran/trace-replay

TraceReplay is an execution tracer for Laravel: instrument steps, view a waterfall timeline, auto-trace jobs/commands, track DB/cache/mail, and deterministically replay HTTP with JSON diffs. Includes PII masking, sampling, multi-tenant scoping, and AI debug prompts.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require iazaran/trace-replay
    

    Publish config and migrations:

    php artisan vendor:publish --provider="Iazaran\TraceReplay\TraceReplayServiceProvider"
    php artisan migrate
    
  2. First Use Case:

    • Enable tracing for a route or controller:
      use Iazaran\TraceReplay\Facades\TraceReplay;
      
      Route::get('/example', function () {
          TraceReplay::start('User Profile Load'); // Start a named trace
          $user = User::with('posts')->find(1);
          TraceReplay::end(); // End the trace
          return view('profile', compact('user'));
      });
      
    • Trigger a replay via the UI (accessible at /trace-replay) or CLI:
      php artisan trace-replay:replay <trace_id>
      
  3. Where to Look First:

    • Dashboard: /trace-replay for visualizing traces.
    • Documentation: Focus on TraceReplay::start()/end() and TraceReplay::instrument() for manual instrumentation.
    • AI Debugging: Use the "AI Fix" button in the UI to generate solutions for errors.

Implementation Patterns

Core Workflows

  1. Automatic Tracing:

    • Enable for all requests via middleware:
      TraceReplay::middleware(function ($request) {
          return TraceReplay::start('Request: ' . $request->path());
      });
      
    • Use TraceReplay::auto() to enable globally (configurable in config/trace-replay.php).
  2. Manual Instrumentation:

    • Granular control over trace steps:
      TraceReplay::instrument('Fetch User Data', function () {
          return User::find(1);
      });
      
    • Contextual data:
      TraceReplay::step('Validate Order', ['order_id' => $order->id]);
      
  3. Replay Integration:

    • Deterministic replay for HTTP requests:
      $trace = TraceReplay::replay('http://example.com/api/order/123');
      
    • Mock external services during replay:
      TraceReplay::mock('Stripe', function ($request) {
          return ['status' => 'paid'];
      });
      
  4. AI-Assisted Debugging:

    • Generate fixes from the UI or programmatically:
      $fix = TraceReplay::ai()->generateFix($traceId, 'Order failed to process');
      
    • Custom prompts:
      TraceReplay::ai()->setModel('anthropic');
      TraceReplay::ai()->setTemperature(0.5);
      

Integration Tips

  • Queue Workers: Wrap queue jobs in TraceReplay::start()/end() for visibility:
    public function handle() {
        TraceReplay::start('Process Payment');
        // Job logic
        TraceReplay::end();
    }
    
  • Event Listeners: Instrument critical events:
    public function handle(OrderPlaced $event) {
        TraceReplay::step('Order Placed', ['order_id' => $event->order->id]);
    }
    
  • Testing: Use TraceReplay::replay() in tests to simulate production flows:
    public function test_order_processing() {
        $trace = TraceReplay::replay('http://example.com/api/orders/1');
        $this->assertEquals('paid', $trace->steps[2]->output['status']);
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Issue: Tracing adds latency. Avoid tracing in high-frequency loops or CLI commands.
    • Fix: Use TraceReplay::auto(false) in production for non-critical paths or enable only for specific routes.
  2. Memory Leaks:

    • Issue: Large payloads (e.g., TraceReplay::step() with big arrays) can bloat storage.
    • Fix: Sanitize data with TraceReplay::mask():
      TraceReplay::step('User Data', [
          'email' => TraceReplay::mask($user->email),
          'password' => '********'
      ]);
      
  3. Replay Determinism:

    • Issue: Non-deterministic operations (e.g., time(), random_int()) break replay.
    • Fix: Mock them during replay:
      TraceReplay::mock('time', fn() => 1625097600);
      
  4. AI Rate Limits:

    • Issue: Free-tier AI models (e.g., OpenAI) may throttle requests.
    • Fix: Cache AI responses:
      TraceReplay::ai()->cacheFor(minutes: 60);
      

Debugging Tips

  • Trace Not Showing?:

    • Verify TraceReplay::start()/end() are called in the correct scope.
    • Check storage/logs/trace-replay.log for initialization errors.
    • Ensure the trace-replay middleware is registered in app/Http/Kernel.php.
  • Replay Failing:

    • Use TraceReplay::replay()->dryRun() to inspect the replay plan before execution.
    • Check for unmocked external calls with TraceReplay::replay()->missingMocks().
  • UI Lag:

    • Optimize trace storage by excluding sensitive data:
      TraceReplay::ignore(function ($step) {
          return in_array($step->name, ['Login', 'Payment']);
      });
      

Extension Points

  1. Custom Steps:

    • Extend with TraceReplay::extend():
      TraceReplay::extend('db', function ($query) {
          return $query->toSql() . ' [' . $query->getBindings() . ']';
      });
      
  2. Storage Backends:

    • Swap the default database storage for Redis or S3:
      TraceReplay::useStorage(\Iazaran\TraceReplay\Storage\RedisStorage::class);
      
  3. AI Providers:

    • Add custom AI models:
      TraceReplay::ai()->addProvider('mistral', [
          'url' => 'https://api.mistral.ai/v1',
          'auth' => fn() => ['Bearer' => config('services.mistral.token')]
      ]);
      
  4. Webhooks:

    • Trigger actions on trace completion:
      TraceReplay::onComplete(function ($trace) {
          if ($trace->hasErrors()) {
              Slack::alert("Trace failed: {$trace->id}");
          }
      });
      

Config Quirks

  • Sampling Rate:
    • Adjust trace_replay.sampling_rate (e.g., 10) to trace 10% of requests in production.
  • Retention:
    • Set trace_replay.retention_days to auto-purge old traces (default: 30).
  • Sensitive Data:
    • Use trace_replay.ignored_paths to exclude routes from tracing:
      'ignored_paths' => [
          'admin/*',
          'api/webhooks/*'
      ],
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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