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

Opentracing Bundle Amqplib Rabbitmq Laravel Package

auxmoney/opentracing-bundle-amqplib-rabbitmq

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Prerequisites: Ensure auxmoney/opentracing-bundle-core and php-amqplib/rabbitmq-bundle are installed.
    composer require auxmoney/opentracing-bundle-core php-amqplib/rabbitmq-bundle
    
  2. Install the extension:
    composer require auxmoney/opentracing-bundle-amqplib-rabbitmq
    
  3. Enable the bundle (Symfony 5+):
    // config/bundles.php
    Auxmoney\OpentracingAmqplibRabbitMqBundle\OpentracingAmqplibRabbitMqBundle::class => ['all' => true],
    

First Use Case

Trace a RabbitMQ message flow:

  • Publish a message with RabbitMQProducer (e.g., via MessageProducerInterface).
  • Consume it with RabbitMQConsumer (e.g., via MessageConsumerInterface).
  • Verify the trace in your APM tool (e.g., Jaeger, Zipkin) to see the automatically propagated span across producer/consumer.

Implementation Patterns

1. Automatic Tracing Integration

  • Producers: The bundle decorates RabbitMQ producers to inject OpenTracing headers (e.g., X-B3-TraceId) into message properties.

    $producer = $this->container->get('rabbit_mq.producer.message');
    $producer->publish(new AmqpMessage('Hello', ['headers' => ['trace_id' => '123']]));
    

    Headers are auto-populated if a trace is active.

  • Consumers: Consumers extract headers and resume the trace context.

    $consumer = $this->container->get('rabbit_mq.consumer.message');
    $consumer->consume(function (AmqpMessage $msg) {
        // Span is automatically resumed here.
        logger()->info('Processing message: ' . $msg->body);
    });
    

2. Customizing Span Tags

Add metadata to spans via message headers or consumer callbacks:

// Producer: Tag the span
$producer->publish(new AmqpMessage('Data', [
    'headers' => [
        'opentracing_span_tags' => json_encode(['component' => 'order-service']),
    ],
]));

// Consumer: Access tags in the callback
$consumer->consume(function (AmqpMessage $msg) {
    $tags = json_decode($msg->getHeaders()['opentracing_span_tags'] ?? '{}', true);
    $this->tracer->activeSpan()->setTag('component', $tags['component'] ?? 'unknown');
});

3. Error Handling

Wrap consumer logic in try-catch to log errors as span tags:

$consumer->consume(function (AmqpMessage $msg) {
    try {
        // Process message...
    } catch (\Exception $e) {
        $this->tracer->activeSpan()->setTag('error', $e->getMessage());
        $this->tracer->activeSpan()->log(['event' => 'error', 'message' => $e->getMessage()]);
        throw $e; // Re-throw to mark span as failed.
    }
});

4. Testing

Mock the tracer in tests:

use OpenTracing\MockTracer;

public function testMessageFlow()
{
    $mockTracer = new MockTracer();
    $this->container->set('opentracing.tracer', $mockTracer);

    // Trigger message flow...
    $spans = $mockTracer->finishedSpans();
    $this->assertCount(2, $spans); // Producer + Consumer spans.
}

Gotchas and Tips

Pitfalls

  1. Missing Core Bundle:

    • The extension requires auxmoney/opentracing-bundle-core. Install it first or expect ServiceNotFoundException.
    • Fix: Run composer require auxmoney/opentracing-bundle-core.
  2. Header Propagation Issues:

    • If spans aren’t linked, verify:
      • The opentracing tracer is active in the producer.
      • Headers aren’t stripped by RabbitMQ (e.g., due to message_properties filtering).
    • Debug: Log headers before publishing:
      logger()->debug('Message headers:', $msg->getHeaders());
      
  3. Symfony 6+ Flex Compatibility:

    • The bundle auto-enables via Flex, but manual config is needed for older Symfony versions.
    • Tip: Use symfony/flex for seamless updates.
  4. PHP 8+ Attributes:

    • The bundle uses PHP 8+ features (e.g., Attribute for decorators). Downgrade if using PHP <8.0.
    • Workaround: Pin to v1.2.0 (pre-PHP8) if needed.

Debugging Tips

  • Enable Tracer Logging:
    # config/packages/opentracing.yaml
    auxmoney_opentracing:
        tracer:
            logging: true  # Logs all spans to Symfony logger.
    
  • Inspect Spans: Use the opentracing.tracer service to manually inspect spans:
    $span = $this->tracer->activeSpan();
    logger()->debug('Current span:', $span->toArray());
    
  • RabbitMQ Bundle Version: Ensure compatibility with php-amqplib/rabbitmq-bundle:^2.10.0. Older versions may break decorator injection.

Extension Points

  1. Custom Propagator: Override the default propagator (e.g., for custom header formats):

    auxmoney_opentracing:
        propagator:
            class: App\Service\CustomRabbitMqPropagator
    

    Implement OpenTracing\Propagation\TextMapPropagator.

  2. Span Naming: Modify span names dynamically:

    $this->tracer->activeSpan()->setOperationName('process_order_' . $orderId);
    
  3. Async Consumers: For async consumers (e.g., RabbitMQAsyncConsumer), ensure the tracer is injected into the worker process:

    $consumer->setWorkerOptions(['tracer' => $this->tracer]);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui