tourze/request-id-bundle

Request ID Generator for Symfony

Installs: 9 029

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:symfony-bundle

0.0.2 2025-04-23 19:02 UTC

This package is auto-updated.

Last update: 2025-05-11 17:47:40 UTC


README

English | 中文

Latest Version Build Status Quality Score Total Downloads

A Symfony bundle for request ID management, enabling tracking and correlation of requests across your application. Supports HTTP, message queue, and CLI commands for comprehensive request tracing in distributed systems.

Features

  • Generate unique request IDs using UUID with Base58 encoding (shorter than standard UUID format)
  • Coroutine-safe request ID storage with automatic reset mechanism to prevent memory leaks
  • Automatically add request ID to HTTP request/response headers
  • Propagate request ID in message queues via Symfony Messenger middleware
  • Generate request ID for CLI commands with special "CLI" prefix
  • Integrate request ID into logs automatically via Monolog processor
  • Support distributed system tracing across different services

Installation

composer require tourze/request-id-bundle

Requirements:

  • PHP >= 8.1
  • Symfony >= 6.4
  • Symfony components: HTTP Kernel, Messenger, Console, Uid
  • Monolog >= 3.1
  • See composer.json for complete dependencies

Quick Start

1. Configuration

# config/packages/request_id.yaml
request_id:
    request_header: 'Request-Id'   # HTTP header to check for incoming request ID
    response_header: 'Request-Id'  # HTTP header to return request ID
    trust_request: true            # whether to trust incoming request ID

2. HTTP Integration

The bundle automatically:

  • Checks for request ID in incoming HTTP headers
  • Generates new ID if none exists or not trusted
  • Sets ID in response headers
  • Stores ID in coroutine-safe storage
// In your controllers, you can access the request ID:
use RequestIdBundle\Service\RequestIdStorage;

class MyController
{
    public function index(RequestIdStorage $requestIdStorage)
    {
        $currentRequestId = $requestIdStorage->getRequestId();
        // Use the request ID...
    }
}

3. Message Queue Integration

Request IDs are automatically propagated through message queues:

// The message will automatically carry the current request ID
$messageBus->dispatch(new MyMessage());

// In message handlers, the original request ID is available:
public function handleMessage(MyMessage $message, RequestIdStorage $requestIdStorage)
{
    $originalRequestId = $requestIdStorage->getRequestId();
    // Process with original request context...
}

4. CLI Support

CLI commands automatically get request IDs with a "CLI" prefix:

$ php bin/console my:command
# A request ID like "CLIxxxxx" will be generated automatically
// In your commands:
use RequestIdBundle\Service\RequestIdStorage;

class MyCommand extends Command
{
    private RequestIdStorage $requestIdStorage;

    public function __construct(RequestIdStorage $requestIdStorage)
    {
        $this->requestIdStorage = $requestIdStorage;
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $commandRequestId = $this->requestIdStorage->getRequestId(); // CLI[uuid]
        // Use request ID...
    }
}

5. Log Integration

Request IDs are automatically added to log records:

$logger->info('Processing user request', ['user_id' => 123]);
// Log output will include "request_id": "7fT9P5RoJ3a..."

How It Works

For a detailed workflow diagram, see WORKFLOW.md.

  1. HTTP Requests:

    • RequestIdSubscriber handles request/response events
    • Checks if request ID exists in headers
    • Uses existing ID if trusted, otherwise generates new one
    • Adds ID to response headers
  2. Message Queue:

    • RequestIdMiddleware intercepts message dispatching/handling
    • Attaches RequestIdStamp to outgoing messages
    • Restores original request ID when consuming messages
    • Cleans up after message handling
  3. CLI Commands:

    • CommandRequestIdSubscriber generates "CLI"-prefixed request ID
    • Sets ID at command start
    • Cleans up at command termination
  4. Log Integration:

    • RequestIdProcessor adds request ID to all log records
    • Makes request ID available in log formatters and outputs

Performance Optimization

  • Uses Base58 encoding for shorter IDs than standard UUIDs
  • Coroutine support ensures thread safety in async environments
  • Automatic cleanup prevents memory leaks in long-running processes
  • Middleware approach avoids performance impact on non-request paths

Contributing

Contributions are welcome! Please see our contribution guidelines for details.

License

The MIT License (MIT). Please see License File for more information.