nowo-tech / correlation-contract
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
Language:Shell
pkg:composer/nowo-tech/correlation-contract
Fund package maintenance!
Requires
- php: >=8.2 <8.6
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- igor-php/igor-php: ^0.10.0 || ^0.11.0
- nowo-tech/phpstan-frankenphp: ^1.4
- phpstan/phpstan: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^11.0
- rector/rector: ^2.0
- symfony/messenger: ^7.4 || ^8.0
Suggests
- symfony/messenger: For Messenger\CorrelationIdStamp (carry the correlation id across message buses); ^7.4 || ^8.0
Provides
None
Conflicts
- symfony/messenger: <7.4
Replaces
None
This package is auto-updated.
Last update: 2026-11-28 16:56:13 UTC
README
⭐ 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.
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:
- 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; - restore the outer id when a nested unit of work (a message handled synchronously during a request) ends;
- 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
- Installation
- Configuration
- Usage
- Contributing
- Code of Conduct
- Changelog
- Upgrading
- Release
- Security
- Engram
- Spec-driven development
- GitHub Spec Kit
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.
