Skip to content

Commit 3f57a13

Browse files
authored
Release/2.0.0 (#2)
1 parent 2804cb9 commit 3f57a13

10 files changed

Lines changed: 273 additions & 189 deletions

‎README.md‎

Lines changed: 50 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
* [How to use](#how-to-use)
88
+ [Wiring the middleware](#wiring-the-middleware)
99
+ [Configuring a custom provider](#configuring-a-custom-provider)
10+
+ [Propagating to outbound boundaries](#propagating-to-outbound-boundaries)
1011
+ [Emitting correlated logs](#emitting-correlated-logs)
12+
* [Concurrency model](#concurrency-model)
1113
* [License](#license)
1214
* [Contributing](#contributing)
1315

@@ -16,13 +18,13 @@
1618
Provides a PSR-15 middleware that guarantees every inbound HTTP request carries a correlation identifier. When the
1719
incoming request already includes a `Correlation-Id` header, the value is reused. Otherwise, a new identifier is
1820
generated through a configurable provider (UUID v7 by default). The correlation ID is exposed as the request
19-
attribute `correlationId` so downstream handlers can read it, and is echoed back through the `Correlation-Id`
20-
response header for end-to-end tracing across services.
21+
attribute `correlationId`, is available through `CorrelationIdMiddleware::correlationId()` for outbound
22+
propagation, and is echoed back through the `Correlation-Id` response header for end-to-end tracing across
23+
services.
2124

22-
The library also ships `CorrelatedLogger`, a thin wrapper over any PSR-3 `LoggerInterface` that resolves the
23-
correlation ID from the request and attaches it to the log context under the `correlation_id` key. This produces
24-
structured logs that can be grouped and filtered by the correlation ID without any extra plumbing in the consumer's
25-
log calls.
25+
The library also ships `CorrelatedLogger`, a PSR-3 `LoggerInterface` decorator that reads the correlation ID at
26+
each log write and attaches it to the log context under the `correlation_id` key. This produces structured logs
27+
that can be grouped and filtered by the correlation ID without any extra plumbing in the consumer's log calls.
2628

2729
## Installation
2830

@@ -49,7 +51,7 @@ use Psr\Http\Server\RequestHandlerInterface;
4951
use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
5052

5153
# Build the middleware with the default UUID v7 provider.
52-
$middleware = CorrelationIdMiddleware::create()->build();
54+
$middleware = CorrelationIdMiddleware::build();
5355

5456
# Process an inbound request through the middleware.
5557
$response = $middleware->process(
@@ -93,45 +95,63 @@ $provider = new readonly class () implements CorrelationIdProvider {
9395
};
9496

9597
# Build the middleware with the custom provider.
96-
$middleware = CorrelationIdMiddleware::create()
97-
->withProvider(provider: $provider)
98-
->build();
98+
$middleware = CorrelationIdMiddleware::build(provider: $provider);
99+
```
100+
101+
### Propagating to outbound boundaries
102+
103+
`CorrelationIdMiddleware::correlationId()` returns the correlation ID of the request in flight. The instance is
104+
stable, so it can be injected once into outbound boundaries (HTTP clients, message payloads), and its `toString()`
105+
reflects, at read time, the identifier the middleware resolved for the request being handled. It reads as an
106+
empty string before any request was handled.
107+
108+
```php
109+
<?php
110+
111+
declare(strict_types=1);
112+
113+
use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
114+
115+
$middleware = CorrelationIdMiddleware::build();
116+
117+
# Inject into outbound clients, message publishers, or bind in the DI container.
118+
$correlationId = $middleware->correlationId();
119+
120+
# Anywhere downstream, while a request is being handled.
121+
$correlationId->toString();
99122
```
100123

101124
### Emitting correlated logs
102125

103-
Uses `CorrelatedLogger` inside a downstream handler so that every log entry automatically carries the request's
104-
correlation ID under the `correlation_id` context key.
126+
Decorates any PSR-3 logger once, at wiring time, with the correlation ID of the request in flight. Every log entry
127+
emitted anywhere in the application automatically carries the `correlation_id` context key, and entries emitted
128+
outside a request (boot, workers) simply omit the key.
105129

106130
```php
107131
<?php
108132

109133
declare(strict_types=1);
110134

111-
use Psr\Http\Message\ResponseInterface;
112-
use Psr\Http\Message\ServerRequestInterface;
113-
use Psr\Http\Server\RequestHandlerInterface;
114-
use Psr\Log\LoggerInterface;
115135
use TinyBlocks\Http\CorrelationId\CorrelatedLogger;
136+
use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
116137

117-
final readonly class PlaceOrderHandler implements RequestHandlerInterface
118-
{
119-
public function __construct(private LoggerInterface $logger)
120-
{
121-
}
122-
123-
public function handle(ServerRequestInterface $request): ResponseInterface
124-
{
125-
# Resolve a PSR-3 logger that attaches the request's correlation ID to every log context.
126-
$logger = CorrelatedLogger::from($this->logger)->resolve($request);
138+
$middleware = CorrelationIdMiddleware::build();
127139

128-
$logger->info('Order placed.', ['order_id' => 42]);
140+
# Decorate the application logger once, at wiring time.
141+
$logger = CorrelatedLogger::from(logger: $applicationLogger, correlationId: $middleware->correlationId());
129142

130-
# ...
131-
}
132-
}
143+
# Anywhere downstream, the entry carries the correlation_id context key.
144+
$logger->info('Order placed.', ['order_id' => 42]);
133145
```
134146

147+
## Concurrency model
148+
149+
`correlationId()` holds one value per middleware instance, which means one value per PHP process. This is correct
150+
on process-per-request runtimes (PHP-FPM, Apache mod_php), where a process handles a single request at a time. On
151+
long-running concurrent runtimes handling several requests in one process (Swoole, RoadRunner worker mode), use
152+
the request attribute `correlationId` (name available as `CorrelationIdMiddleware::ATTRIBUTE_NAME`), which is
153+
isolated per request by construction.
154+
135155
## License
136156

137157
Http Correlation Id is licensed under [MIT](LICENSE).

‎composer.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
},
3333
"require-dev": {
3434
"ergebnis/composer-normalize": "^2.52",
35-
"guzzlehttp/psr7": "^2.9",
35+
"guzzlehttp/psr7": "^2.12",
3636
"infection/infection": "^0.33",
3737
"phpstan/phpstan": "^2.2",
3838
"phpunit/phpunit": "^13.1",

‎src/CorrelatedLogger.php‎

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,51 +4,44 @@
44

55
namespace TinyBlocks\Http\CorrelationId;
66

7-
use Psr\Http\Message\ServerRequestInterface;
7+
use Psr\Log\AbstractLogger;
88
use Psr\Log\LoggerInterface;
9-
use TinyBlocks\Http\CorrelationId\Internal\CorrelationAttachingLogger;
9+
use Stringable;
1010

1111
/**
12-
* Wraps a PSR-3 logger so that log entries emitted during request handling automatically carry
13-
* the request's correlation identifier in the log context.
12+
* PSR-3 logger that attaches the correlation ID of the request in flight to every log context
13+
* under the <code>correlation_id</code> key.
1414
*/
15-
final readonly class CorrelatedLogger
15+
final class CorrelatedLogger extends AbstractLogger
1616
{
17-
private function __construct(private LoggerInterface $logger)
18-
{
17+
private function __construct(
18+
private readonly LoggerInterface $logger,
19+
private readonly CorrelationId $correlationId
20+
) {
1921
}
2022

2123
/**
22-
* Creates a CorrelatedLogger from a PSR-3 logger.
24+
* Creates a CorrelatedLogger from a PSR-3 logger and a correlation ID.
2325
*
2426
* @param LoggerInterface $logger The underlying logger to delegate writes to.
27+
* @param CorrelationId $correlationId The correlation ID read at each log write, typically the one
28+
* exposed by {@see CorrelationIdMiddleware::correlationId()}.
2529
* @return CorrelatedLogger The created instance.
2630
*/
27-
public static function from(LoggerInterface $logger): CorrelatedLogger
31+
public static function from(LoggerInterface $logger, CorrelationId $correlationId): CorrelatedLogger
2832
{
29-
return new CorrelatedLogger(logger: $logger);
33+
return new CorrelatedLogger(logger: $logger, correlationId: $correlationId);
3034
}
3135

32-
/**
33-
* Returns a PSR-3 logger that attaches the request's correlation ID to every log context.
34-
*
35-
* <p>When the request has no <code>correlationId</code> attribute, or the attribute is not a
36-
* {@see CorrelationId} instance, the underlying logger is returned unchanged.</p>
37-
*
38-
* @param ServerRequestInterface $request The request whose correlation ID should be attached.
39-
* @return LoggerInterface A logger that emits log entries carrying the correlation ID.
40-
*/
41-
public function resolve(ServerRequestInterface $request): LoggerInterface
36+
public function log($level, string|Stringable $message, array $context = []): void
4237
{
43-
$correlationId = $request->getAttribute('correlationId');
38+
$correlationId = $this->correlationId->toString();
4439

45-
if (!$correlationId instanceof CorrelationId) {
46-
return $this->logger;
40+
if ($correlationId === '') {
41+
$this->logger->log($level, $message, $context);
42+
return;
4743
}
4844

49-
return new CorrelationAttachingLogger(
50-
logger: $this->logger,
51-
correlationId: $correlationId->toString()
52-
);
45+
$this->logger->log($level, $message, [...$context, 'correlation_id' => $correlationId]);
5346
}
5447
}

‎src/CorrelationId.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
namespace TinyBlocks\Http\CorrelationId;
66

77
/**
8-
* Represents an immutable correlation identifier used to trace a request across service boundaries.
8+
* Correlation identifier used to trace a request across service boundaries.
99
*/
1010
interface CorrelationId
1111
{

‎src/CorrelationIdMiddleware.php‎

Lines changed: 38 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,40 +8,41 @@
88
use Psr\Http\Message\ServerRequestInterface;
99
use Psr\Http\Server\MiddlewareInterface;
1010
use Psr\Http\Server\RequestHandlerInterface;
11+
use TinyBlocks\Http\CorrelationId\Internal\RequestScopedCorrelationId;
1112
use TinyBlocks\Http\CorrelationId\Internal\UuidCorrelationId;
13+
use TinyBlocks\Http\CorrelationId\Internal\UuidCorrelationIdProvider;
1214

1315
/**
14-
* PSR-15 middleware that reads or generates a correlation identifier, exposes it as a request attribute,
15-
* and echoes it back through the <code>Correlation-Id</code> response header for downstream tracing.
16+
* PSR-15 middleware that reads or generates a correlation identifier, exposes it as a request attribute
17+
* and through {@see CorrelationIdMiddleware::correlationId()}, and echoes it back through the
18+
* <code>Correlation-Id</code> response header for downstream tracing.
1619
*/
1720
final readonly class CorrelationIdMiddleware implements MiddlewareInterface
1821
{
22+
/**
23+
* Name of the request attribute carrying the resolved {@see CorrelationId}.
24+
*/
25+
public const string ATTRIBUTE_NAME = 'correlationId';
26+
1927
private const string HEADER_NAME = 'Correlation-Id';
20-
private const string ATTRIBUTE_NAME = 'correlationId';
2128

22-
private function __construct(private CorrelationIdProvider $provider)
23-
{
29+
private function __construct(
30+
private CorrelationIdProvider $provider,
31+
private RequestScopedCorrelationId $correlationId
32+
) {
2433
}
2534

2635
/**
27-
* Builds a CorrelationIdMiddleware from a correlation ID provider.
36+
* Builds a CorrelationIdMiddleware from an optional correlation ID provider.
2837
*
29-
* @param CorrelationIdProvider $provider The strategy used to generate a new correlation ID when absent.
38+
* @param CorrelationIdProvider $provider The strategy used to generate a new correlation ID when the
39+
* request carries none. Defaults to a UUID v7 provider.
3040
* @return CorrelationIdMiddleware The configured middleware instance.
3141
*/
32-
public static function build(CorrelationIdProvider $provider): CorrelationIdMiddleware
33-
{
34-
return new CorrelationIdMiddleware(provider: $provider);
35-
}
36-
37-
/**
38-
* Creates a CorrelationIdMiddlewareBuilder for fluent configuration.
39-
*
40-
* @return CorrelationIdMiddlewareBuilder The builder instance.
41-
*/
42-
public static function create(): CorrelationIdMiddlewareBuilder
43-
{
44-
return new CorrelationIdMiddlewareBuilder();
42+
public static function build(
43+
CorrelationIdProvider $provider = new UuidCorrelationIdProvider()
44+
): CorrelationIdMiddleware {
45+
return new CorrelationIdMiddleware(provider: $provider, correlationId: new RequestScopedCorrelationId());
4546
}
4647

4748
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
@@ -52,8 +53,25 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
5253
: $this->provider->generate();
5354

5455
$request = $request->withAttribute(self::ATTRIBUTE_NAME, $correlationId);
56+
$this->correlationId->assign(correlationId: $correlationId);
57+
5558
$response = $handler->handle($request);
5659

5760
return $response->withHeader(self::HEADER_NAME, $correlationId->toString());
5861
}
62+
63+
/**
64+
* Returns the correlation ID of the request in flight.
65+
*
66+
* <p>The returned instance is stable across the middleware's lifetime and reflects, at read time,
67+
* the identifier resolved for the request being handled. Share it with outbound boundaries (HTTP
68+
* clients, message payloads, loggers) to propagate the identifier. It reads as an empty string
69+
* before any request was handled.</p>
70+
*
71+
* @return CorrelationId The correlation ID of the request in flight.
72+
*/
73+
public function correlationId(): CorrelationId
74+
{
75+
return $this->correlationId;
76+
}
5977
}

‎src/CorrelationIdMiddlewareBuilder.php‎

Lines changed: 0 additions & 39 deletions
This file was deleted.

‎src/Internal/CorrelationAttachingLogger.php‎

Lines changed: 0 additions & 23 deletions
This file was deleted.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TinyBlocks\Http\CorrelationId\Internal;
6+
7+
use TinyBlocks\Http\CorrelationId\CorrelationId;
8+
9+
final class RequestScopedCorrelationId implements CorrelationId
10+
{
11+
private ?CorrelationId $correlationId = null;
12+
13+
public function assign(CorrelationId $correlationId): void
14+
{
15+
$this->correlationId = $correlationId;
16+
}
17+
18+
public function toString(): string
19+
{
20+
return $this->correlationId?->toString() ?? '';
21+
}
22+
}

0 commit comments

Comments
 (0)