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

Technical Evaluation

Architecture Fit

  • Immutable, execution-scoped context propagation aligns perfectly with Laravel’s middleware stack, async workers (Swoole/fibers), and event-driven architectures (Laravel Echo, ReactPHP). The package’s design mirrors OpenTelemetry’s specification for context, ensuring compatibility with distributed tracing systems.
  • Baggage support enables attaching custom metadata (e.g., tenant_id, user_id) to traces, which is critical for Laravel’s multi-tenant and user-specific workflows. This integrates seamlessly with Laravel’s existing request()->user() or auth()->tenant() patterns.
  • Fiber and event-loop support is a game-changer for Laravel apps using Swoole, Amp, or ReactPHP, where manual context management in callbacks is error-prone. The bindContext() utility abstracts this complexity, reducing boilerplate.
  • Middleware integration: The package’s implicit propagation model fits Laravel’s middleware pipeline (Kernel.php), where each request naturally inherits and propagates context through the stack.

Integration Feasibility

  • Low-risk for synchronous Laravel apps: The core Context::activate()/detach() pattern can be adopted incrementally in middleware, services, or repositories without disrupting existing flows.
  • Async Laravel (Swoole/fibers): Requires enabling OTEL_PHP_FIBERS_ENABLED and preloading vendor/autoload.php (for non-CLI SAPIs). This is a one-time configuration change with minimal runtime overhead.
  • Event loops (ReactPHP/Amp): The bindContext() helper provides a drop-in solution for wrapping callbacks, though custom event loop integrations may need adjustments for performance-sensitive use cases.
  • Queue workers (Horizon/Swoole): Context propagation across job dispatches and retries is automatic with proper setup, eliminating the need for manual trace ID passing in job payloads.

Technical Risk

Risk Area Assessment Mitigation
Fiber/Event Loop Overhead Fiber support requires NTS PHP + ext-ffi, which may not be available in all hosting environments. Event loop integrations (ReactPHP/Amp) could introduce subtle bugs if not tested rigorously. Phase rollout: Start with synchronous middleware, then test fibers/Swoole in staging. Provide fallback mechanisms (e.g., disable fibers if ext-ffi is missing).
Context Leaks Improper detach() calls or early exits (e.g., die()) can cause memory leaks or lost traces. Debug scopes warn in dev but may not catch all edge cases. Enable OTEL_PHP_DEBUG_SCOPES_DISABLED in production only after thorough testing. Use try-finally blocks religiously and validate context cleanup in CI.
PHP Version Compatibility Drops PHP 7.4/8.0 support; requires PHP 8.1+. Laravel 9+ is compatible, but legacy apps may need upgrades. Audit Laravel/PHP version matrix. If upgrading is infeasible, evaluate alternatives like stack/stack (but lose OpenTelemetry compliance).
Async Race Conditions Concurrent fibers/event loops may lead to context corruption if not properly synchronized. Test with high-concurrency workloads (e.g., load-test WebSocket gateways). Use Context::getCurrent() defensively in async code.
Baggage Propagation Custom baggage (e.g., tenant_id) must be explicitly set and propagated. Missing baggage in downstream services breaks trace correlation. Document baggage requirements in API contracts. Use Laravel’s request()->attributes or app()->bind() to sync baggage with existing context.
Vendor Lock-in OpenTelemetry is open, but some backends (e.g., Datadog) may require proprietary extensions. Evaluate backend compatibility early. Use OTLP (OpenTelemetry Protocol) for maximum portability.

Key Questions

  1. Async Strategy:

    • Are we using Swoole, fibers, ReactPHP, or Amp? If yes, how will we test context propagation under load?
    • Do we need custom event loop integrations, or will bindContext() suffice?
  2. Observability Backend:

    • Which OpenTelemetry-compatible backend (Jaeger, Datadog, Lightstep) will we use? Are there proprietary extensions needed?
    • How will we correlate traces with Laravel’s existing logging (Monolog, Sentry)?
  3. Laravel Ecosystem:

    • Which components (HTTP, queues, WebSockets, CLI) need instrumentation first? Prioritize based on debugging pain points.
    • How will we sync baggage (e.g., tenant_id) with Laravel’s auth/tenant systems?
  4. Performance:

    • What is the acceptable overhead for context propagation? Benchmark in staging.
    • Will fiber/event loop integrations meet latency requirements (e.g., real-time WebSockets)?
  5. Compliance:

    • Do we need traceable user actions for GDPR/PCI DSS? If so, how will baggage map to Laravel’s data models?
    • Are there audit requirements for trace retention or export?
  6. Team Readiness:

    • Does the team have OpenTelemetry experience, or will training be needed?
    • How will we monitor context propagation in production (e.g., dropped traces, leaks)?

Integration Approach

Stack Fit

  • Laravel Core:

    • Middleware: Wrap Context::activate()/detach() around the middleware pipeline to propagate traces for HTTP requests.
    • Service Container: Bind Context to Laravel’s container for dependency injection (e.g., app(Context::class)).
    • Request/Response: Use Context::getBaggage() to attach/detach metadata (e.g., request()->attributes ↔ baggage).
  • Async Laravel:

    • Swoole/Fibers: Enable OTEL_PHP_FIBERS_ENABLED and preload autoload.php. Test with Swoole\Coroutine or PHP fibers.
    • Event Loops: Integrate bindContext() with ReactPHP/Amp loops. For custom loops, implement Context::getCurrent() restoration.
    • Queues: Propagate context across job dispatches using Context::storeInBaggage() and Context::extractFromBaggage().
  • HTTP Clients:

    • Guzzle/Symfony HTTP Client: Use OpenTelemetry’s Propagator to inject/extract trace context in headers.
    • Laravel HTTP Client: Extend the client to auto-propagate context via middleware.
  • CLI/Artisan:

    • Wrap Artisan::command() in Context::activate() to trace CLI workflows (e.g., php artisan queue:work).
  • WebSockets:

    • Instrument Laravel Echo/Pusher to propagate context in event payloads (e.g., authenticate middleware).

Migration Path

Phase Components Actions Dependencies
Phase 1 Synchronous Laravel 1. Add open-telemetry/context and opentelemetry-php/sdk.2. Instrument middleware to propagate traces.3. Test HTTP requests and CLI commands. Laravel 9+, PHP 8.1+, OpenTelemetry SDK.
Phase 2 Async Workers (Queues, Swoole) 1. Enable fiber support (OTEL_PHP_FIBERS_ENABLED).2. Wrap job dispatches in Context::activate().3. Test queue retries and Swoole coroutines. Swoole extension, ext-ffi (if using fibers).
Phase 3 Event Loops (ReactPHP/Amp) 1. Integrate bindContext() with event loops.2. Test WebSocket gateways and async APIs. ReactPHP/Amp, custom event loop code.
Phase 4 Baggage and Custom Metadata 1. Attach baggage (e.g., tenant_id) in middleware.2. Sync with Laravel’s auth/tenant systems.3. Validate trace correlation across services. OpenTelemetry exporter (Jaeger/Datadog).
Phase 5 Observability Backend Integration 1. Configure OTLP/Jaeger/Datadog exporter.2. Validate end-to-end traceability.3. Set up alerts for dropped traces. Backend-specific SDK (e.g., ddtrace for Datadog).

Compatibility

  • Laravel Versions:
    • Supported: Laravel 9+ (PHP 8.1+). Laravel 8 may work but lacks fiber support.
    • Legacy: Laravel 7/
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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