Search by

nowo-tech / correlation-contract

HecFranco

Framework-free correlation id contract: the CorrelationId value object, CorrelationIdProviderInterface (current id per request, message or command, FrankenPHP worker safe), a Null provider, header names (X-Correlation-Id, W3C traceparent) and an optional Symfony Messenger stamp. No dependencies beyo

Package info

github.com/nowo-tech/correlation-contract

Documentation

Language:Shell

pkg:composer/nowo-tech/correlation-contract

Fund package maintenance!

HecFranco

Statistics

Installs: 2 726

Dependents: 5

Suggesters: 1

Stars: 0

Open Issues: 0

v0.1.0 2026-11-28 07:10 UTC

This package is auto-updated.

Last update: 2026-11-28 16:56:13 UTC


README

CI Packagist Version Packagist Downloads License PHP GitHub stars Coverage

⭐ Found this useful? Install from Packagist · Give it a star on GitHub so more developers can find it.

A framework-free contract for one correlation id per request, message or command. Packages that log, audit, queue or trace work (an audit trail, an HTTP log, a task board) all tag what they write with the same id, so one search finds everything a single request caused, across HTTP, Messenger and the console. No dependencies beyond PHP; the optional Messenger stamp needs symfony/messenger.

FrankenPHP friendly

This package is FrankenPHP worker mode friendly.

Who does what

Role Who What
Implements The host application's integration layer (one per application) A CorrelationIdProviderInterface that reads or creates the id at the HTTP edge, when a message is received and when a command starts, and resets it afterwards
Consumes Reusable packages (bundles, kits, DDD modules) An optional port: type-hint CorrelationIdProviderInterface, default to NullCorrelationIdProvider, store current()?->toString() next to what they write

A consuming package never creates or propagates ids itself: when the host binds no provider, it simply records none.

Installation

composer require nowo-tech/correlation-contract

PHP 8.2–8.6. For Messenger\CorrelationIdStamp also symfony/messenger ^7.4 || ^8.0 (in suggest only).

Format

CorrelationId is an immutable value object: 1 to 64 characters out of A-Z a-z 0-9 . _ : - (CorrelationId::PATTERN). A W3C trace id (32 lowercase hex), a UUID and a ULID all fit; the value is kept exactly as given and compared case-sensitively. The format excludes spaces, control characters and anything that could break a header, a log line or a URL.

use Nowo\CorrelationContract\CorrelationId;

$id = CorrelationId::fromString('01HZX3J9K6Q8R2T4V6W8Y0A2C4'); // throws InvalidArgumentException when invalid
$id = CorrelationId::tryFromString($request->headers->get('X-Correlation-Id')); // null when absent or invalid
$id = CorrelationId::generate();                         // 32 lowercase hex from random_bytes()
$id->toString(); (string) $id; $id->equals($other);

Header names

Constant Value Use
Headers::CORRELATION_ID X-Correlation-Id Read on incoming requests, sent on responses and outgoing requests
Headers::TRACEPARENT traceparent W3C Trace Context interop

traceparent mapping. A traceparent is version-traceid-parentid-flags, e.g. 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01. Its 32-hex trace-id identifies the whole distributed trace, so it becomes the correlation id: CorrelationId::tryFromTraceparent($header) returns it, or null for an invalid header (version ff, extra fields on version 00, an all-zero trace-id or parent-id, uppercase hex). The recommended order at the edge is: a valid X-Correlation-Id, else the trace-id of a valid traceparent, else generate(). Ids from generate() have the trace-id shape, so a host can also start a traceparent from them; it never builds a traceparent from an id that is not 32 hex.

Incoming ids are untrusted: always parse them with tryFromString() / tryFromTraceparent() and fall back to a new id; never echo an invalid value back.

The provider and worker-mode rules

interface CorrelationIdProviderInterface
{
    public function current(): ?CorrelationId;          // null outside any request, message or command
    public function currentOrGenerate(): CorrelationId; // a new id outside any (not stored)
}

In a long-running worker (FrankenPHP worker mode, RoadRunner, Messenger consumers) one provider instance serves many units of work. An implementation must:

  1. set the id when a request, message or command starts and clear it when it ends, including on failure (a terminate / handled / failed listener plus a reset hook such as Symfony's kernel.reset): no id may leak into the next request or message;
  2. restore the outer id when a nested unit of work (a message handled synchronously during a request) ends;
  3. not store the id currentOrGenerate() creates outside any unit of work.

Consumers must not keep the returned id in their own properties: ask the provider every time.

NullCorrelationIdProvider is stateless: current() is always null and currentOrGenerate() returns a new random id on every call.

Causation

CorrelationContext carries the correlationId (the same along a whole chain: request, the messages it dispatches, the messages those dispatch) and an optional causedBy, the id of the event or message one step back. A consumer that records both can rebuild the tree of a chain. It is a plain value object, so the provider interface stays two methods; an implementation that tracks causation passes a context where a consumer accepts one.

use Nowo\CorrelationContract\CorrelationContext;

$context = new CorrelationContext($provider->currentOrGenerate());
$next = $context->withCausedBy(CorrelationId::fromString($messageId));

Messenger stamp (optional)

Messenger\CorrelationIdStamp implements Symfony\Component\Messenger\Stamp\StampInterface and carries a correlationId plus an optional causedBy. It is only usable when symfony/messenger is installed; nothing else in the package references it. The host's integration adds it when it dispatches and makes its id current while the handler runs:

use Nowo\CorrelationContract\Messenger\CorrelationIdStamp;

$bus->dispatch($message, [new CorrelationIdStamp($provider->currentOrGenerate())]);

// In a middleware of the receiving side:
$stamp = $envelope->last(CorrelationIdStamp::class);
$context = $stamp?->toContext();   // or CorrelationIdStamp::fromContext($context) when dispatching

Consuming the port in a package

use Nowo\CorrelationContract\CorrelationIdProviderInterface;
use Nowo\CorrelationContract\NullCorrelationIdProvider;

final readonly class AuditRecorder
{
    public function __construct(
        private AuditStore $store,
        private CorrelationIdProviderInterface $correlation = new NullCorrelationIdProvider(),
    ) {
    }

    public function record(string $action): void
    {
        $this->store->add($action, correlationId: $this->correlation->current()?->toString());
    }
}

In a Symfony bundle, register NullCorrelationIdProvider as the default service for the interface alias and let the host override the alias. Store the id as a nullable VARCHAR(64) column.

Backward-compatibility promise

0.x is the first release line: the API may still change in a minor (0.y) release, with an UPGRADING note. From 1.0 the format, the header names, the interface signatures, the constructor parameter order of CorrelationContext and Messenger\CorrelationIdStamp and the named constructors are frozen for the major.

What is here

Class Role
CorrelationId Value object: fromString(), tryFromString(), generate(), tryFromTraceparent(), toString(), equals()
CorrelationIdProviderInterface The port: current(), currentOrGenerate()
NullCorrelationIdProvider Default: never a current id, generates on demand
CorrelationContext Correlation id + optional causedBy
Headers CORRELATION_ID, TRACEPARENT
Messenger\CorrelationIdStamp Optional Messenger stamp (needs symfony/messenger)

Documentation

Additional documentation

Tests and coverage

  • Tests: PHPUnit (tests/Unit), CI on PHP 8.2–8.6
  • PHP: 100% of lines and methods (gate make test-coverage-100, CI)
  • TS/JS: N/A
  • Python: N/A

License

MIT. See LICENSE.