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 Steps

  1. Installation:

    composer require open-telemetry/context
    

    Ensure PHP 8.1+ is used (fiber support requires PHP 8.1+).

  2. First Use Case: Activate a context scope in a Laravel middleware or controller to propagate trace IDs:

    use OpenTelemetry\Context\Context;
    use OpenTelemetry\Context\Scope;
    
    public function handle(Request $request, Closure $next): Response
    {
        $scope = Context::getCurrent()->activate();
        try {
            return $next($request);
        } finally {
            $scope->detach();
        }
    }
    
  3. Where to Look First:

    • README.md for core usage patterns.
    • OpenTelemetry PHP SDK for integration with instrumentation libraries.
    • OpenTelemetry\Context\Context class for API reference.

Implementation Patterns

Core Workflows

1. HTTP Request Propagation

Use middleware to inject and propagate context:

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

Tip: Register this middleware globally in app/Http/Kernel.php.

2. Async Context Propagation

  • Fibers: Enable with OTEL_PHP_FIBERS_ENABLED=true and ext-ffi:
    // Preload autoloader for non-CLI SAPIs if ffi.enable=preload
    require __DIR__ . '/vendor/autoload.php';
    
  • Event Loops: Use bindContext() for callbacks:
    $loop->addPeriodicTimer(1, bindContext(function () {
        // Context is automatically propagated
    }));
    

3. Queue Job Context

Propagate context to Horizon/queue workers:

// app/Providers/AppServiceProvider.php
public function boot()
{
    Queue::before(function (JobProcessing $event) {
        $scope = Context::getCurrent()->activate();
        try {
            $event->job->handle();
        } finally {
            $scope->detach();
        }
    });
}

4. Baggage for Custom Metadata

Attach metadata (e.g., user_id) to traces:

$context = Context::getCurrent()
    ->withBaggageItem('user_id', auth()->id());
$scope = $context->activate();

Integration Tips

  • Guzzle HTTP Client: Use OpenTelemetry\Instrumentation\Guzzle to auto-propagate context.
  • Database Queries: Integrate with opentelemetry-php/db for SQL trace spans.
  • Laravel Echo: Propagate context to WebSocket events via Pusher/Ably adapters.
  • Artisan Commands: Activate context in handle():
    public function handle()
    {
        $scope = Context::getCurrent()->activate();
        try {
            // Command logic
        } finally {
            $scope->detach();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Forgotten detach():

    • Symptom: Debug scopes warn in non-production (OTEL_PHP_DEBUG_SCOPES_DISABLED disables this).
    • Fix: Always use try-finally blocks. For async code, use bindContext() wrappers.
  2. Fiber Context Leaks:

    • Symptom: Context not propagated to new fibers (NTS build required).
    • Fix: Set OTEL_PHP_FIBERS_ENABLED=true and ensure ext-ffi is enabled.
  3. ZTS (Thread-Safe) PHP:

    • Symptom: Fiber observers fail with FFI errors.
    • Fix: Use a non-ZTS PHP build or avoid fiber context propagation in ZTS environments.
  4. Non-CLI SAPIs with ffi.enable=preload:

    • Symptom: Autoloader not preloaded, leading to fiber context failures.
    • Fix: Manually require vendor/autoload.php before fiber creation.
  5. Baggage Size Limits:

    • Symptom: Large baggage items may exceed OpenTelemetry limits.
    • Fix: Limit baggage to essential metadata (e.g., user_id, tenant_id).

Debugging Tips

  • Enable Debug Scopes:

    OTEL_PHP_DEBUG_SCOPES_DISABLED=false php artisan your:command
    
    • Helps track missing detach() calls in development.
  • Inspect Current Context:

    dd(Context::getCurrent()->getBaggage()->all());
    
  • Check Fiber Support:

    if (!Context::isFiberSupportEnabled()) {
        throw new RuntimeException('Fiber context propagation not enabled. Set OTEL_PHP_FIBERS_ENABLED=true.');
    }
    

Extension Points

  1. Custom Context Storage:

    • Implement OpenTelemetry\Context\ContextStorageInterface for non-standard storage (e.g., Redis).
  2. Response Propagator:

    • Use the experimental ResponsePropagatorInterface (v1.4.0+) to inject context into HTTP responses:
      $propagator = new ResponsePropagator();
      $propagator->inject($context, $response);
      
  3. Environment Context:

    • Access/set environment-specific context (e.g., tenant isolation):
      $context = Context::getCurrent()
          ->withEnvironment('tenant_id', $tenantId);
      
  4. TextMap Propagation:

    • Extend OpenTelemetry\Context\Propagator\TextMapPropagator for custom carrier formats (e.g., gRPC metadata).

Configuration Quirks

  • Disable Debug Scopes in Production:

    OTEL_PHP_DEBUG_SCOPES_DISABLED=true php artisan queue:work
    
    • Avoids notices when exit/die prevents detach().
  • Fiber Preloading:

    • For Swoole/ReactPHP, ensure vendor/autoload.php is preloaded if ffi.enable=preload is set.
  • Baggage Serialization:

    • Baggage items are serialized to strings. Avoid complex objects; use JSON strings for structured data:
      $context->withBaggageItem('metadata', json_encode(['key' => 'value']));
      
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