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

Context Laravel Package

open-telemetry/context

OpenTelemetry Context for PHP: immutable, execution-scoped context propagation for tracing and telemetry. Activate/detach scopes for implicit propagation, with debug warnings for scope leaks. Supports async apps with fiber-based propagation and event loop binding.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require open-telemetry/context
    
  2. Activate a context in your Laravel middleware, service, or command:

    use OpenTelemetry\Context\Context;
    use OpenTelemetry\Context\Scope;
    
    $context = Context::getCurrent();
    $scope = $context->activate();
    try {
        // Your code here (e.g., HTTP request, queue job, fiber)
    } finally {
        $scope->detach(); // Critical: Always detach!
    }
    
  3. First Use Case: Instrument a Laravel HTTP request to propagate trace context:

    // In a middleware or controller
    $scope = Context::getCurrent()->activate();
    try {
        $response = Http::get('https://api.example.com/endpoint');
        return response()->json($response->json());
    } finally {
        $scope->detach();
    }
    

Key Entry Points

  • Context::getCurrent(): Retrieve the current context (e.g., for middleware, services).
  • Context::withBaggage(): Attach custom metadata (e.g., user_id, tenant_id) to traces.
  • Context::withSpan(): Create or modify spans (requires opentelemetry-php/sdk).
  • bindContext(): Wrap async callbacks (fibers, event loops) for automatic propagation.

Implementation Patterns

1. Laravel HTTP Requests

Pattern: Propagate context via middleware or HTTP clients (Guzzle, Symfony).

// app/Http/Middleware/TraceContext.php
public function handle($request, Closure $next) {
    $scope = Context::getCurrent()->activate();
    try {
        return $next($request);
    } finally {
        $scope->detach();
    }
}

Integration Tip:

  • Use OpenTelemetry\Context\Propagation\TextMapPropagator to inject/extract context from headers (e.g., traceparent).
  • Example for Guzzle:
    $client = new Client([
        'on_request' => function (RequestInterface $request) {
            $propagator = new TextMapPropagator();
            $propagator->inject(Context::getCurrent(), $request->getHeaders());
        },
    ]);
    

2. Async Workflows (Fibers, Swoole, Event Loops)

Pattern: Automate context propagation in async code.

Fibers (PHP 8.1+)

Enable with:

OTEL_PHP_FIBERS_ENABLED=true php your_script.php

Example:

// In a fiber or Swoole coroutine
$fiber = new Fiber(function () {
    $scope = Context::getCurrent()->activate();
    try {
        // Fiber logic (context auto-propagated)
    } finally {
        $scope->detach();
    }
});
$fiber->start();

Event Loops (ReactPHP/Amp)

Pattern: Use bindContext() to wrap callbacks.

use OpenTelemetry\Context\bindContext;

// ReactPHP example
$loop = React\EventLoop\Factory::create();
$loop->addPeriodicTimer(1, bindContext(function () {
    // Context automatically propagated
}));

Integration Tip:

  • For Swoole, use Swoole\Coroutine::create(bindContext(fn() => {...})).
  • Avoid memory leaks by detaching scopes in finally blocks.

3. Queue Jobs (Horizon, Laravel Queues)

Pattern: Propagate context to async jobs.

// In your job class
public function handle() {
    $scope = Context::getCurrent()->activate();
    try {
        // Job logic
    } finally {
        $scope->detach();
    }
}

Integration Tip:

  • Use OpenTelemetry\Context\Propagation\TextMapPropagator to inject context into job payloads (serialized).
  • For Horizon, extend Supervisor to auto-activate context.

4. CLI Commands (Artisan)

Pattern: Attach baggage to CLI commands for traceability.

// In a command
protected function handle() {
    $context = Context::getCurrent()->withBaggage([
        'command' => 'your:command',
        'user_id' => auth()->id(),
    ]);
    $scope = $context->activate();
    try {
        // Command logic
    } finally {
        $scope->detach();
    }
}

5. Baggage for Custom Metadata

Pattern: Attach business metadata to traces.

$context = Context::getCurrent()->withBaggage([
    'tenant_id' => 'acme-corp',
    'request_id' => $request->header('X-Request-ID'),
]);
$context->activate();

Use Cases:

  • Correlate logs, database queries, and external API calls.
  • Pass user/tenant context to async workers.

Gotchas and Tips

Pitfalls

  1. Forgetting to Detach Scopes

    • Issue: Undetached scopes leak memory and may cause warnings in dev.
    • Fix: Always use try-finally:
      $scope = $context->activate();
      try {
          // ...
      } finally {
          $scope->detach(); // Critical!
      }
      
    • Debugging: Enable OTEL_PHP_DEBUG_SCOPES_DISABLED=false (default) to catch leaks in dev.
  2. Async Context Loss

    • Issue: Fibers/event loops may lose context if not wrapped with bindContext().
    • Fix: Use bindContext() for all async callbacks:
      $loop->addTimer(1, bindContext(fn() => {...}));
      
  3. PHP 8.1+ Required for Fibers

    • Issue: Fiber support requires PHP 8.1+ and ext-ffi.
    • Fix: Check PHP_VERSION_ID >= 80100 and enable OTEL_PHP_FIBERS_ENABLED.
  4. Serialization/Deserialization

    • Issue: Context is not serializable (e.g., for queues).
    • Fix: Use TextMapPropagator to inject context into headers/payloads:
      $propagator = new TextMapPropagator();
      $carrier = [];
      $propagator->inject(Context::getCurrent(), $carrier);
      // Serialize $carrier with job payload
      
  5. ZTS (Thread-Safety) Issues

    • Issue: FFI-based fiber observers may fail in ZTS builds.
    • Fix: Use NTS (Non-Thread-Safe) PHP builds for fiber support.

Debugging Tips

  1. Inspect Current Context

    $context = Context::getCurrent();
    dump($context->getBaggage()->all()); // View baggage
    dump($context->getSpan()); // View active span (if SDK is loaded)
    
  2. Enable Debug Scopes

    • Set OTEL_PHP_DEBUG_SCOPES_DISABLED=false to catch undetached scopes in dev.
  3. Check Fiber Context

    • Verify fiber context propagation with:
      $fiber = new Fiber(function () {
          dump(Context::getCurrent()->getBaggage()->all());
      });
      $fiber->start();
      
  4. Validate Propagation

    • Use TextMapPropagator to verify context injection/extraction:
      $propagator = new TextMapPropagator();
      $carrier = [];
      $propagator->inject($context, $carrier);
      $extracted = $propagator->extract([]); // Should match $context
      

Extension Points

  1. Custom Propagators

    • Implement PropagatorInterface for non-TextMap formats (e.g., gRPC metadata).
  2. Context Storage

    • Override ContextStorage for custom storage backends (e.g., Redis for distributed contexts).
  3. Baggage Validation

    • Extend Baggage to add custom validation rules:
      $baggage = new Baggage([
          'user_id' => '123',
      ]);
      $baggage->validate(fn($key, $value) => is_numeric($value)); // Custom rule
      
  4. Async Hooks

    • Extend bindContext() for custom async systems (e.g., custom event loops).

Performance Considerations

  1. Avoid Heavy Baggage

    • Limit baggage size to reduce overhead in async contexts.
  2. Scope Granularity

    • Prefer fine-grained scopes (e.g., per-request) over coarse-grained (e.g., app-wide).
  3. Fiber Overhead

    • Fiber context propagation adds ~50–100µs overhead per fiber. Benchmark in high-throughput apps.
  4. Disable Debug in Production

    • Set OTEL_PHP_DEBUG_SCOPES_DISABLED=true to avoid warnings in prod.
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony