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. Activate a context to create a scope and safely detach it (try/finally). Includes debug scope warnings, and optional async support for fibers and event loops.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Immutable, execution-scoped context propagation aligns perfectly with Laravel’s middleware stack, HTTP clients (Guzzle), and async workflows (queues, fibers). The package’s adherence to the OpenTelemetry specification ensures compatibility with existing or future observability tools (e.g., Jaeger, Datadog).
  • Baggage support enables attaching custom metadata (e.g., tenant_id, user_id) to traces, which is critical for multi-tenant Laravel applications or compliance-driven use cases.
  • Fiber/event-loop integration is a game-changer for Laravel apps using Swoole, ReactPHP, or PHP 8.1+ fibers. The bindContext() pattern automates context propagation in async callbacks, reducing boilerplate and errors.

Integration Feasibility

  • Laravel Middleware: The package’s Context::activate()/detach() pattern maps cleanly to Laravel’s middleware lifecycle. Wrap middleware logic in a try/finally block to ensure context restoration.
    public function handle($request, Closure $next) {
        $scope = Context::getCurrent()->activate();
        try {
            return $next($request);
        } finally {
            $scope->detach();
        }
    }
    
  • HTTP Clients (Guzzle): Integrate with Guzzle’s middleware to propagate context across outbound requests:
    $stack = HandlerStack::create();
    $stack->push(Middleware::mapRequest(function (RequestInterface $request) {
        return $request->withHeader('otel-context', Context::getCurrent()->getBaggage()->toString());
    }));
    
  • Queues/Jobs: Automatically propagate context to dispatched jobs using Laravel’s dispatchSync or by wrapping job execution in activate()/detach().
  • Artisan Commands: Ensure CLI commands (e.g., php artisan queue:work) inherit the root context by initializing it early in the bootstrap process.

Technical Risk

Risk Area Mitigation Strategy
Fiber/Async Complexity Test thoroughly with Swoole/ReactPHP. Use OTEL_PHP_FIBERS_ENABLED cautiously in production.
Debug Scopes in Prod Disable via OTEL_PHP_DEBUG_SCOPES_DISABLED if exit/die is used (not recommended).
Memory Leaks Monitor ContextStorageNode GC after detach() (fixed in v1.2.1).
PHP Version Compatibility Drop PHP 7.4/8.0 support (already done); ensure PHP 8.1+ for fibers.
Vendor Lock-in Adhere to OpenTelemetry spec; avoid custom extensions.

Key Questions

  1. Async Workloads:

    • Are we using fibers (PHP 8.1+), Swoole, or event loops (ReactPHP/Amp)? If yes, how will we test bindContext() in production?
    • Example: Does our WebSocket gateway (Laravel Echo) need context propagation to Pusher callbacks?
  2. Observability Stack:

    • Which OpenTelemetry backend are we using (Jaeger, Datadog, etc.)? Does it support baggage propagation?
    • Example: Will we attach tenant_id to traces for multi-tenant apps?
  3. Laravel Ecosystem:

    • How will we ensure context flows through third-party packages (e.g., Spatie’s queue adapters, Laravel Horizon)?
    • Example: Does our payment gateway integration (e.g., Stripe) need trace correlation?
  4. Performance:

    • What’s the overhead of activate()/detach() in high-throughput scenarios (e.g., 10K RPS)?
    • Benchmark: Compare with/without context propagation in load tests.
  5. Debugging:

    • How will we handle missing detach() calls in production? (Debug scopes emit warnings by default.)
    • Tradeoff: Disable debug scopes (OTEL_PHP_DEBUG_SCOPES_DISABLED) but risk silent leaks.
  6. Future-Proofing:

    • Are we planning to extend observability beyond traces (e.g., metrics, logs)? Baggage can carry metadata for these.
    • Example: Will we use Context::getBaggage() to attach user_id to logs for correlation?

Integration Approach

Stack Fit

  • Laravel Core: The package’s middleware-friendly design fits seamlessly into Laravel’s request lifecycle. Use it to:
    • Propagate context through HTTP requests (via middleware).
    • Correlate database queries (e.g., with spatie/laravel-query-logger).
    • Trace Artisan commands (e.g., php artisan migrate).
  • Async Layers:
    • Fibers: Enable OTEL_PHP_FIBERS_ENABLED and preload vendor/autoload.php for non-CLI SAPIs.
    • Event Loops: Implement bindContext() for ReactPHP/Amp callbacks.
    • Queues: Wrap job execution in activate()/detach() or use Laravel’s dispatchSync with context.
  • HTTP Clients: Integrate with Guzzle’s middleware to propagate context headers (e.g., otel-context).
  • Database: Use baggage to attach trace IDs to query logs or audit tables (e.g., trace_id column).

Migration Path

Phase Action Items Dependencies
Phase 1: Core Tracing 1. Add open-telemetry/context and opentelemetry-php/sdk to composer.json. OpenTelemetry backend (Jaeger/Datadog).
2. Instrument middleware to activate context on incoming requests. Laravel middleware stack.
3. Propagate context to HTTP clients (Guzzle) via headers. Guzzle middleware.
Phase 2: Async Support 4. Enable fiber support (OTEL_PHP_FIBERS_ENABLED) for PHP 8.1+ apps. PHP 8.1+, ext-ffi.
5. Implement bindContext() for event loops (ReactPHP/Amp). Event loop library.
6. Wrap queue jobs in activate()/detach() or use dispatchSync with context. Laravel Queues.
Phase 3: Extended Observability 7. Attach baggage (e.g., tenant_id) to traces/logs for correlation. OpenTelemetry exporter.
8. Integrate with logging (Monolog) to include trace IDs in logs. Monolog processor.

Compatibility

  • Laravel Versions: Tested with Laravel 9+ (PHP 8.1+). Older versions may require polyfills for fibers.
  • PHP Extensions:
    • Required: ext-ffi for fiber support (PHP 8.1+).
    • Optional: ext-swoole/ext-react for async integrations.
  • OpenTelemetry SDK: Ensure compatibility with opentelemetry-php/sdk (v1.x+).
  • Third-Party Packages: May need wrappers to propagate context (e.g., Spatie’s queue adapters).

Sequencing

  1. Start with Synchronous Workflows:
    • Instrument middleware, HTTP clients, and Artisan commands first.
    • Validate trace propagation across Laravel’s core layers.
  2. Add Async Support:
    • Enable fibers/event loops after core tracing is stable.
    • Test bindContext() with Swoole/ReactPHP in staging.
  3. Extend to Observability:
    • Attach baggage to logs/metrics last to avoid over-engineering.
    • Use baggage for compliance/auditing (e.g., user_id in logs).

Operational Impact

Maintenance

  • Dependencies:
    • Monitor open-telemetry/context for breaking changes (e.g., PHP 8.2+ support).
    • Update opentelemetry-php/sdk in lockstep to avoid compatibility issues.
  • Debugging:
    • Debug scopes emit warnings for missing detach() in non-production. Disable via OTEL_PHP_DEBUG_SCOPES_DISABLED if needed (tradeoff: silent leaks).
    • Use Context::getCurrent()->debugDump() for troubleshooting.
  • Configuration:
    • Environment variables:
      • OTEL_PHP_DEBUG_SCOPES_DISABLED: Disable debug warnings.
      • OTEL_PHP_FIBERS_ENABLED: Enable fiber support (PHP 8.1+).

Support

  • Common Issues:
    • Missing detach(): Wrap activate() in try/finally blocks.
    • Fiber leaks: Ensure vendor/autoload.php is preloaded for non-CLI SAPIs.
    • Context not propagated: Verify middleware/HTTP clients include the otel-context header.
  • Tooling:
    • Integrate
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport