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

Correlation Bundle Laravel Package

aubes/correlation-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**: Add the package via Composer:
   ```bash
   composer require aubes/correlation-bundle

The bundle auto-registers via Symfony Flex, requiring no additional configuration for basic usage.

  1. First Use Case: Access the correlation ID in a service:

    use Aubes\CorrelationBundle\Storage\CorrelationIdProviderInterface;
    
    final class MyService
    {
        public function __construct(
            private readonly CorrelationIdProviderInterface $provider
        ) {}
    
        public function logSomething(): void
        {
            $correlationId = $this->provider->get();
            // Use $correlationId in logs, metrics, or other observability tools
        }
    }
    
  2. Verify HTTP Propagation: Send a request to your Symfony app and check the X-Correlation-Id header in the response. If missing, the bundle auto-generates one.

  3. Debugging: Run the debug command to inspect active integrations and the current correlation ID:

    php bin/console correlation:debug
    

Implementation Patterns

Core Workflow

  1. Request Entry: The bundle automatically captures the X-Correlation-Id header (configurable) on incoming HTTP requests. If missing, it generates a new ID.
  2. Storage: The CorrelationIdStorage (injected as CorrelationIdProviderInterface or CorrelationIdStorageInterface) holds the ID in a request-scoped context. It memoizes the ID on first access and validates all writes.
  3. Propagation: Integrations (e.g., Monolog, Messenger) automatically inject the ID into their respective contexts (logs, messages, etc.) without manual intervention.

Common Patterns

HTTP Client Integration

  • Outgoing Requests: The correlation ID is automatically forwarded as a header (e.g., X-Correlation-Id) to external services via Symfony's HTTP Client.
    # config/packages/correlation.yaml
    correlation:
        http_client:
            enabled: true
            clients: ['http_client', 'custom_client']  # Target specific clients
    
  • Override Behavior: Use force_header: false to allow caller-provided headers to override the bundle's ID (useful for testing or external systems).

Monolog Integration

  • Log Correlation: The ID is added to every log record under the extra array with a configurable field name (default: correlation_id).
    correlation:
        monolog:
            enabled: true
            field_name: 'trace_id'  # Customize the log field name
            channels: ['!event']    # Exclude specific channels
    

Messenger Integration

  • Message Stamping: The ID is attached to dispatched messages and restored when consumed (critical for async workflows).
    correlation:
        messenger:
            enabled: true
            buses: ['async']       # Target specific buses
    

Console Commands

  • Manual Override: Pass a custom ID via CLI:
    php bin/console my:command --correlation-id=custom123
    
  • Auto-Generation: If no ID is provided, the bundle generates one automatically.

Custom Generators

  • UUID vs Hex: Choose between UuidCorrelationIdGenerator (default) or Hex32CorrelationIdGenerator for W3C Trace Context compatibility.
    correlation:
        generator: 'Aubes\CorrelationBundle\Generator\Hex32CorrelationIdGenerator'
    
  • Custom Logic: Implement CorrelationIdGeneratorInterface for domain-specific ID generation:
    final class AppGenerator implements CorrelationIdGeneratorInterface
    {
        public function generate(): string
        {
            return bin2hex(random_bytes(16)); // Example: 32-char hex
        }
    }
    
    correlation:
        generator: 'App\Generator\AppGenerator'
    

Seed from External Sources

  • Override Default Behavior: Inject CorrelationIdStorageInterface to set an ID from an external source (e.g., Kafka message, database):
    use Aubes\CorrelationBundle\Storage\CorrelationIdStorageInterface;
    
    final class ExternalService
    {
        public function __construct(
            private readonly CorrelationIdStorageInterface $storage
        ) {}
    
        public function processExternalData(string $externalId): void
        {
            try {
                $this->storage->set($externalId); // Validate and set
            } catch (InvalidCorrelationIdException) {
                // Fallback to auto-generation
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Header Name Mismatch:

    • If the incoming X-Correlation-Id header uses a different name (e.g., X-Request-ID), update the config:
      correlation:
          http:
              header_name: 'X-Request-ID'
      
    • Debug Tip: Use correlation:debug to verify the active header name.
  2. Worker Mode Conflicts:

    • The storage implements ResetInterface, but long-running workers (e.g., Messenger workers) may leak IDs across requests. Ensure workers reset the storage explicitly or rely on Symfony's request-scoped container.
  3. HTTP Client Overrides:

    • With force_header: true (default), the bundle always overwrites caller-provided headers. Disable this if external systems require their own IDs:
      correlation:
          http_client:
              force_header: false
      
  4. Monolog Channel/Handler Exclusions:

    • Empty channels or handlers arrays apply to all channels/handlers. Explicitly list channels to include (e.g., ['api', 'cli']) or exclude (e.g., ['!event']).
  5. Twig Template Access:

    • The correlation_id() Twig function is not available by default in all templates. Ensure the Twig integration is enabled:
      correlation:
          twig:
              enabled: true
      
    • Gotcha: If using Twig globally (e.g., in emails), ensure the storage is initialized before rendering.
  6. UUID Version Mismatch:

    • The uuid_version config (4, 6, or 7) is ignored for non-UUID generators. Validate your generator's output format matches expectations.

Debugging Tips

  1. Web Profiler Panel:

    • Enable the Symfony Profiler to see the correlation ID source (generated/provided) and active integrations in the "Correlation ID" panel.
  2. Log Inspection:

    • Check Monolog logs for the correlation_id field (default name). If missing, verify the integration is enabled and the channel/handler is included.
  3. Messenger Debugging:

    • For async issues, use the Messenger transport logs to confirm the ID is stamped on dispatch and restored on consumption:
      php bin/console messenger:consume async -vv
      
  4. Custom Generator Validation:

    • Ensure your CorrelationIdGeneratorInterface implementation returns printable ASCII strings (1–255 chars). The bundle throws InvalidCorrelationIdException for invalid IDs.

Extension Points

  1. Custom Integrations:

    • Extend the bundle by implementing a new integration. Follow the existing patterns (e.g., HttpClientIntegration, MonologIntegration) and register it as a service tagged with correlation.integration.
  2. Storage Decorators:

    • Decorate CorrelationIdStorageInterface to add pre/post-logic (e.g., logging ID changes, analytics):
      final class AnalyticsStorage implements CorrelationIdStorageInterface
      {
          public function __construct(
              private readonly CorrelationIdStorageInterface $decorated
          ) {}
      
          public function set(string $id): void
          {
              $this->decorated->set($id);
              // Log or track the ID change
          }
      
          // Delegate other methods...
      }
      
      Register the decorator in services.yaml:
      services:
          Aubes\CorrelationBundle\Storage\CorrelationIdStorageInterface: '@analytics_storage'
          analytics_storage:
              decorates: 'Aubes\CorrelationBundle\Storage\CorrelationIdStorage'
              arguments: ['@analytics_storage.inner']
      
  3. Dynamic Configuration:

    • Override the generator or header name dynamically (e.g., per environment) using Symfony's parameter system:
      # config/packages/dev/correlation.yaml
      correlation:
          http:
              header_name: 'X-Dev-Correlation-Id'
      
  4. Testing:

    • Mock the storage to inject fixed IDs in tests:
      $storage = $this->createMock(CorrelationIdStorageInterface::class);
      $storage->method('get')->willReturn('test-123');
      $this->container->set(CorrelationIdStorageInterface::class, $storage);
      
    • Use the --correlation-id CLI option to test command behavior:
      php bin/console my:command --correlation-id=test-id
      

Performance Notes

  • Memoization: The storage generates the ID once on first access (get()), reducing overhead in
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