symfony-nats-messenger 5.12: a worker's own inbox prefix
(php, symfony, nats, release-notes) 24 min read by Bartosz Pachołek
5.12.0 adds inbox_prefix, so a worker's NATS user can be granted its own prefix instead of _INBOX.>, a grant that let it read other workers' pulled messages. We show both. Plus 5.11.1: a worker that may not pull now says so, and retry_via: nak survives a silent server.
symfony-nats-messenger 5.12.0 is out, with one new option. inbox_prefix moves every inbox the transport's NATS client subscribes to under a prefix of its own, so a worker's NATS user can be granted worker-a.> instead of _INBOX.>. The second grant is wider than it looks: it lets a worker read the replies of every other client in the account, the messages their pulls receive included. Below we show that happening, then lock it down.
Our last post covered symfony-nats-messenger 5.11, so this one also covers 5.11.1, a patch release with two fixes for workers that miss a permission or an answer. We ran every example on PHP 8.5.9 against nats-server 2.15.3 in Docker, with Symfony Messenger 8.2.0 and php-nats-jetstream-client 2.42.0. We installed 5.11.0, 5.11.1 and 5.12.0 from Packagist side by side with the same composer.lock, so only the transport differs, plus one more 5.11.0 install on client 2.36.0 for the "before" of a 5.11.1 fix. The outputs are pasted as they came out.

What 5.12 is for
A NATS client receives answers on inboxes: subjects it subscribes to and names as the reply address of what it sends. The transport uses two kinds. The request inbox, _INBOX.<id>.*, is where the replies of setup(), the acknowledgement of each send(), the count behind messenger:stats and an ack_sync acknowledgement arrive. And each pull gets an inbox of its own, _INBOX.JS.FETCH.<id>, where JetStream delivers the pulled messages.
So a worker's NATS user needs permission to subscribe there, and the grant that covers both is _INBOX.>. But NATS permissions are about subjects, not connections. _INBOX.> lets that user subscribe to every inbox under _INBOX, those of every other client in the same account included. Any worker can read what the others pull.
The usual answer in NATS is a prefix per user: each client puts its inboxes under its own prefix, and its user may subscribe only there. The client has long had NatsOptions::inboxPrefix, and since 2.39.1 its pull inboxes follow it too (our php-nats-jetstream-client 2.40 post covers that patch). The transport had no way to pass a prefix on, and since 5.10.0 it refuses options it does not know. 5.12.0 adds inbox_prefix and requires client 2.39.1 or later.
Proof of concept: what _INBOX.> lets a neighbour read
One NATS server and five users, for a local test only (each password is the user name):
services:
nats:
image: nats:2.15.3-alpine
command: ["-c", "/etc/nats/server.conf"]
ports: ["14781:4222"]
volumes: ["./server.conf:/etc/nats/server.conf:ro"]
server_name: shop
port: 4222
jetstream {
store_dir: "/data"
}
authorization {
ADMIN = { publish = ">", subscribe = ">" }
# What every worker needed up to 5.11: the reply inboxes of the whole account.
ALL_INBOXES = { publish = ">", subscribe = "_INBOX.>" }
# A worker limited to its own inbox prefix.
OWN_INBOX = { publish = ">", subscribe = "worker-a.>" }
# Everything but a pull from the consumer "worker" of the stream "orders".
NO_PULL = {
publish = { allow = ">", deny = "$JS.API.CONSUMER.MSG.NEXT.orders.worker" }
subscribe = ">"
}
users = [
{ user: admin, password: admin, permissions: $ADMIN }
{ user: shipping, password: shipping, permissions: $ALL_INBOXES }
{ user: billing, password: billing, permissions: $ALL_INBOXES }
{ user: worker-a, password: worker-a, permissions: $OWN_INBOX }
{ user: nopull, password: nopull, permissions: $NO_PULL }
]
}
Every user may publish anywhere, to keep the file short; a real worker needs only the subjects the README lists under "Permissions a Worker Needs". What differs is where they may subscribe. shipping and billing are workers set up the way every worker had to be up to 5.11: _INBOX.>. worker-a may subscribe only under worker-a.>. nopull is for a later section.
The project needs only the transport:
{
"require": {
"idct/symfony-nats-messenger": "^5.12"
}
}
The script lets billing do what its grant allows: subscribe to _INBOX.> and listen. Then shipping sends an order with a customer's e-mail address in it and pulls it, and worker-a does the same with inbox_prefix: worker-a:
<?php
// What a grant of "_INBOX.>" lets another worker of the account read.
// billing listens on _INBOX.> while shipping and worker-a each send and pull an order.
// Run: php neighbour.php (needs the server of compose.yaml, symfony-nats-messenger 5.12)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Core\NatsMessage;
use IDCT\NATS\Core\SubscriptionQueue;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
final class OrderPlaced
{
public function __construct(public readonly int $order, public readonly string $email)
{
}
}
const SERVER = '127.0.0.1:14781/orders/orders.placed?consumer=worker';
function dsn(string $user): string
{
return "nats-jetstream://$user:$user@" . SERVER . '&max_batch_timeout=1';
}
/** Prints what billing's subscription to _INBOX.> received since the last call. */
function overheard(SubscriptionQueue $inbox): void
{
$seen = 0;
while (($message = $inbox->next()) !== null) {
assert($message instanceof NatsMessage);
$seen++;
if (preg_match('/[a-z]+@example\.com/', $message->payload, $email) === 1) {
$what = sprintf('a pulled message with %s in it', $email[0]);
} elseif ($message->payload === '') {
$what = trim(strtok((string) $message->rawHeaders, "\r\n"));
} else {
$what = strlen($message->payload) > 40
? substr($message->payload, 0, 37) . '...'
: $message->payload;
}
printf(" billing got on %s:\n %s\n", $message->subject, $what);
}
if ($seen === 0) {
echo " billing got nothing\n";
}
}
$client = (new NatsTransportConfigurationBuilder())->build(dsn('admin'))->client;
$client->connect()->await();
try {
$client->jetStream()->deleteStream('orders')->await();
} catch (Throwable) {
}
$client->disconnect()->await();
$admin = new NatsTransport(dsn('admin'), [], new PhpSerializer());
$admin->setup();
$admin->close();
// billing is a worker set up the pre-5.12 way: it may subscribe to _INBOX.>.
$billing = (new NatsTransportConfigurationBuilder())->build(dsn('billing'))->client;
$billing->connect()->await();
$inbox = $billing->subscribeQueue('_INBOX.>')->await();
$billing->flush()->await();
$inbox->setTimeout(0.5);
$workers = [
'shipping' => [7, '[email protected]', []],
'worker-a' => [8, '[email protected]', ['inbox_prefix' => 'worker-a']],
];
foreach ($workers as $user => [$order, $email, $options]) {
$label = 'inbox_prefix: ' . ($options['inbox_prefix'] ?? 'none');
$worker = new NatsTransport(dsn($user), $options, new PhpSerializer());
$worker->send(new Envelope(new OrderPlaced($order, $email)));
$got = 0;
while (($batch = [...$worker->get()]) !== []) {
foreach ($batch as $envelope) {
$worker->ack($envelope);
$got++;
}
}
printf("%s (%s) sent order %d, pulled and acked %d\n", $user, $label, $order, $got);
$worker->close();
overheard($inbox);
}
$billing->disconnect()->await();
Run it:
docker compose up --detach
composer install
php neighbour.php
shipping (inbox_prefix: none) sent order 7, pulled and acked 1
billing got on _INBOX.02e9b57861ae45ec283ac6fa.0:
{"stream":"orders","seq":1}
billing got on orders.placed:
a pulled message with [email protected] in it
billing got on _INBOX.JS.FETCH.c5d83df0976e20a2f8d7b1a9:
NATS/1.0 408 Request Timeout
worker-a (inbox_prefix: worker-a) sent order 8, pulled and acked 1
billing got nothing
billing got three messages meant for shipping: the acknowledgement of its send, the pulled order with the customer's address in it, and the 408 that ended the pull. The order shows up under the subject it was stored under, orders.placed, because that is how JetStream delivers a pulled message to the pull's inbox; it reached billing because _INBOX.> matches that inbox. Nothing in NATS tells shipping that another subscriber got its replies.
worker-a's traffic went to worker-a.<id>.* and worker-a.JS.FETCH.<id>, which _INBOX.> does not match, and billing's user has no grant under worker-a.> to subscribe there instead.
A user limited to its own prefix, before and after
The other half of the question: can a worker run with nothing but worker-a.>? inbox-prefix.php lets the admin set up the stream and send order 1, then tries as worker-a, first without the option and then with it:
<?php
// The user worker-a may subscribe only under "worker-a.>", not "_INBOX.>".
// Run: php inbox-prefix.php (needs the server of compose.yaml)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
final class OrderPlaced
{
public function __construct(public readonly int $order)
{
}
}
const SERVER = '127.0.0.1:14781/orders/orders.placed?consumer=worker';
function dsn(string $user): string
{
return "nats-jetstream://$user:$user@" . SERVER . '&max_batch_timeout=1';
}
function report(string $what, Throwable $e): void
{
$line = sprintf('%s: %s: %s', $what, (new ReflectionClass($e))->getShortName(),
$e->getMessage());
echo ' ', wordwrap($line, 84, "\n ", true), "\n";
}
printf(
"symfony-nats-messenger %s, php-nats-jetstream-client %s\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client'),
);
// The admin starts from an empty stream and sends order 1.
$client = (new NatsTransportConfigurationBuilder())->build(dsn('admin'))->client;
$client->connect()->await();
try {
$client->jetStream()->deleteStream('orders')->await();
} catch (Throwable) {
}
$client->disconnect()->await();
$admin = new NatsTransport(dsn('admin'), [], new PhpSerializer());
$admin->setup();
$admin->send(new Envelope(new OrderPlaced(1)));
$cases = ['without inbox_prefix' => [], 'inbox_prefix: worker-a' => [
'inbox_prefix' => 'worker-a',
]];
$order = 1;
foreach ($cases as $label => $options) {
echo "worker-a, $label\n";
try {
$worker = new NatsTransport(dsn('worker-a'), $options, new PhpSerializer());
} catch (Throwable $e) {
report('build', $e);
continue;
}
try {
$worker->send(new Envelope(new OrderPlaced(++$order)));
echo " send: order $order stored\n";
} catch (Throwable $e) {
report("send of order $order", $e);
}
printf(
" messenger:stats shows %d (the admin's shows %d)\n",
$worker->getMessageCount(),
$admin->getMessageCount(),
);
try {
$orders = [];
while (($batch = [...$worker->get()]) !== []) {
foreach ($batch as $envelope) {
$orders[] = $envelope->getMessage()->order;
$worker->ack($envelope);
}
}
printf(" get: orders %s received and acked\n", implode(', ', $orders));
printf(" messenger:stats shows %d\n", $worker->getMessageCount());
} catch (Throwable $e) {
report('get', $e);
}
$worker->close();
}
$admin->close();
On 5.11.1 (php inbox-prefix.php):
symfony-nats-messenger v5.11.1, php-nats-jetstream-client v2.42.0
worker-a, without inbox_prefix
send of order 2: ConnectionException: request/reply is unavailable on this
connection: the shared reply-inbox subscription "_INBOX.<inbox>.*" was rejected by
the server (permissions violation). Grant the account subscribe permission for the
reply-inbox wildcard "_INBOX.>" to use request()/requestMany().
messenger:stats shows 0 (the admin's shows 2)
get: ConnectionException: JetStream pull fetch failed: the server rejected its
reply-inbox subscription "_INBOX.JS.FETCH.fe4012d7d911355476fa4997": 'Permissions
Violation for Subscription to "_INBOX.JS.FETCH.fe4012d7d911355476fa4997"'
worker-a, inbox_prefix: worker-a
build: InvalidArgumentException: Unknown option 'inbox_prefix' in the options of the
NATS transport. See "Configuration Options" in the README for the options it takes.
Without the option, send() fails because the server refuses the request inbox, messenger:stats reads 0 while the admin counts 2, and get() fails on the pull's inbox. A worker with that user could not do anything. 5.11.1 refuses the option itself, as it refuses any option it does not know.
Look at the admin's count, though: 2. The send() of order 2 threw, and the order was stored anyway. The publish went out; only its acknowledgement had nowhere to arrive. A send that throws is no proof that nothing was stored, which is the case the transport's deduplicate option was made for (see our symfony-nats-messenger 5.4 post).
On 5.12.0:
symfony-nats-messenger v5.12.0, php-nats-jetstream-client v2.42.0
worker-a, without inbox_prefix
send of order 2: ConnectionException: request/reply is unavailable on this
connection: the shared reply-inbox subscription "_INBOX.<inbox>.*" was rejected by
the server (permissions violation). Grant the account subscribe permission for the
reply-inbox wildcard "_INBOX.>" to use request()/requestMany().
messenger:stats shows 0 (the admin's shows 2)
get: ConnectionException: JetStream pull fetch failed: the server rejected its
reply-inbox subscription "_INBOX.JS.FETCH.7a4b8c7566f5b01ebb3a5e92": 'Permissions
Violation for Subscription to "_INBOX.JS.FETCH.7a4b8c7566f5b01ebb3a5e92"'
worker-a, inbox_prefix: worker-a
send: order 3 stored
messenger:stats shows 3 (the admin's shows 3)
get: orders 1, 2, 3 received and acked
messenger:stats shows 0
The same refusals without the option. With inbox_prefix: worker-a, the same user sends order 3, counts 3, receives orders 1, 2 and 3, acknowledges them and counts 0. The stored order 2 from the failed send is the second one it received.
Setting it up
In a Symfony application inbox_prefix goes under the transport's options, into the DSN query, or comes from %env()%, like the other options. The transport checks the value when it is built. This script tries a few values, then the DSN form, as worker-a:
<?php
// Which inbox_prefix values the transport takes, and the DSN query form.
// Run: php prefix-check.php (needs the server of compose.yaml)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NatsMessenger\NatsTransport;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
final class OrderPlaced
{
public function __construct(public readonly int $order)
{
}
}
$dsn = 'nats-jetstream://worker-a:[email protected]:14781/orders/orders.placed'
. '?consumer=worker&max_batch_timeout=1';
$prefixes = ['acc.w1', ' worker-a ', '', 'worker-a.', 'a..b', 'worker.*', 'my inbox'];
foreach ($prefixes as $prefix) {
$label = var_export($prefix, true);
try {
$options = ['inbox_prefix' => $prefix];
(new NatsTransport($dsn, $options, new PhpSerializer()))->close();
printf("%-12s accepted\n", $label);
} catch (Throwable $e) {
$line = sprintf('%-12s %s', $label, $e->getMessage());
echo wordwrap($line, 86, "\n ", true), "\n";
}
}
// The same option from the DSN query: worker-a sends and pulls one order.
$transport = new NatsTransport("$dsn&inbox_prefix=worker-a", [], new PhpSerializer());
$transport->setup();
$transport->send(new Envelope(new OrderPlaced(4)));
$got = [];
while (($batch = [...$transport->get()]) !== []) {
foreach ($batch as $envelope) {
$got[] = $envelope->getMessage()->order;
$transport->ack($envelope);
}
}
printf("?inbox_prefix=worker-a in the DSN: setup, send, get of order %s\n", ...$got);
$transport->close();
'acc.w1' accepted
' worker-a ' accepted
'' The inbox_prefix option must be a non-empty string.
'worker-a.' Invalid inbox_prefix option 'worker-a.'. An inbox prefix is a subject of
non-empty tokens, without whitespace, control characters, "*" or ">".
'a..b' Invalid inbox_prefix option 'a..b'. An inbox prefix is a subject of
non-empty tokens, without whitespace, control characters, "*" or ">".
'worker.*' Invalid inbox_prefix option 'worker.*'. An inbox prefix is a subject of
non-empty tokens, without whitespace, control characters, "*" or ">".
'my inbox' Invalid inbox_prefix option 'my inbox'. An inbox prefix is a subject of
non-empty tokens, without whitespace, control characters, "*" or ">".
?inbox_prefix=worker-a in the DSN: setup, send, get of order 4
The value is trimmed. An empty one, a leading, trailing or double dot, a wildcard and whitespace inside the value are refused when the transport is built. Without that check the client would refuse them too, but only at each worker's first request, after a deploy.
What to grant, from the README's new section "A User Limited to Its Own Inbox Prefix":
- One grant covers both inboxes:
<prefix>.>. A grant of<prefix>.*.*covers only the request inbox, since the pull inbox has three tokens after the prefix. - Give each user a prefix of its own. Every user granted
<prefix>.>can read what arrives under it, so a shared prefix brings the problem back. - A NATS failure transport is a transport of its own, with its own client and options. The worker's
inbox_prefixdoes not reach it: give it its own when its user is limited the same way.
5.11.1: a worker that may not pull says so
A worker pulls by publishing to $JS.API.CONSUMER.MSG.NEXT.<stream>.<consumer>. A user who may not publish there gets each pull refused with a permissions violation, and the server keeps the connection open. Up to client 2.36.0 such a pull then waited out its expiry and ended as an empty one, and get() read that as "nothing to do". refused-pull.php runs Symfony's Worker as nopull, the user the server config above denies exactly that subject, with one message waiting and a time limit of 5 seconds. It and the next script also need symfony/event-dispatcher:
<?php
// A worker whose NATS user may not pull from its consumer (the user nopull), run
// through Symfony's Worker for at most 5 s. Run: php refused-pull.php
// (needs the server of ../inbox-prefix/compose.yaml)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\EventListener\StopWorkerOnTimeLimitListener;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
use Symfony\Component\Messenger\Worker;
final class OrderPlaced
{
public function __construct(public readonly int $order)
{
}
}
const SERVER = '127.0.0.1:14781/orders/orders.placed?consumer=worker';
function dsn(string $user): string
{
return "nats-jetstream://$user:$user@" . SERVER
. '&max_batch_timeout=1&auto_setup=false';
}
function short(Throwable $e): string
{
return (new ReflectionClass($e))->getShortName();
}
$client = (new NatsTransportConfigurationBuilder())->build(dsn('admin'))->client;
$client->connect()->await();
try {
$client->jetStream()->deleteStream('orders')->await();
} catch (Throwable) {
}
$client->disconnect()->await();
$admin = new NatsTransport(dsn('admin'), [], new PhpSerializer());
$admin->setup();
$admin->send(new Envelope(new OrderPlaced(1)));
printf(
"symfony-nats-messenger %s, client %s, messenger:consume as nopull\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client'),
);
$handled = 0;
$bus = new MessageBus([new HandleMessageMiddleware(new HandlersLocator([
OrderPlaced::class => [function () use (&$handled): void {
$handled++;
}],
]))]);
$events = new EventDispatcher();
$events->addSubscriber(new StopWorkerOnTimeLimitListener(5));
$transport = new NatsTransport(dsn('nopull'), [], new PhpSerializer());
$start = microtime(true);
$since = fn (): float => microtime(true) - $start;
try {
(new Worker(['orders' => $transport], $bus, $events))->run(['sleep' => 100000]);
printf("the worker ran %.1f s and ended without an error\n", $since());
} catch (Throwable $e) {
printf("the worker stopped after %.1f s:\n", $since());
$line = short($e) . ': ' . $e->getMessage();
echo ' ', wordwrap($line, 84, "\n ", true), "\n";
if ($e->getPrevious() !== null) {
echo ' previous: ', short($e->getPrevious()), "\n";
}
}
printf("handled: %d, messenger:stats shows %d\n", $handled, $admin->getMessageCount());
$transport->close();
$admin->close();
On 5.11.0 with client 2.36.0, what an application locked before these releases runs (php refused-pull.php):
symfony-nats-messenger v5.11.0, client v2.36.0, messenger:consume as nopull
the worker ran 6.0 s and ended without an error
handled: 0, messenger:stats shows 1
The worker idled for its whole time limit, handled nothing, and ended without an error, with the message still waiting. messenger:consume exits 0 in that case, and a supervisor starts it again into the same silence.
Client 2.36.1 fails such a pull as soon as it reads the refusal (our php-nats-jetstream-client 2.37 post shows it), so even 5.11.0 stops on today's client, with the client's own exception:
symfony-nats-messenger v5.11.0, client v2.42.0, messenger:consume as nopull
the worker stopped after 0.0 s:
PermissionViolationException: The server refused the pull to
"$JS.API.CONSUMER.MSG.NEXT.orders.worker": Permissions Violation for Publish to
"$JS.API.CONSUMER.MSG.NEXT.orders.worker". No message was delivered for it. Grant
this connection's user permission to publish to
"$JS.API.CONSUMER.MSG.NEXT.orders.worker".
handled: 0, messenger:stats shows 1
5.11.1 turns it into Messenger's TransportException, which names the stream, the consumer and the subject to grant, and keeps the client's exception as the previous one:
symfony-nats-messenger v5.11.1, client v2.42.0, messenger:consume as nopull
the worker stopped after 0.0 s:
TransportException: Cannot pull from NATS stream "orders", consumer "worker". Grant
the worker permission to publish to "$JS.API.CONSUMER.MSG.NEXT.orders.worker".
previous: PermissionViolationException
handled: 0, messenger:stats shows 1
5.11.1 requires client 2.36.1 or later, so the worker stops either way. Two refusals the client still does not see, per the README: a pull that has already received a message goes on to its usual end, so the worker's next pull is the one that fails; and a refusal whose subject the client cannot match to the pull's (a subject the account maps to another one, or a stream or consumer name the server writes with \u escapes) still ends as an empty pull.
5.11.1: retry_via: nak and a consumer that does not answer
With retry_via: nak (new in 5.9.0), Symfony's retry strategy decides and NATS carries the retry out: the transport NAKs the failed delivery with Symfony's delay. The last delivery the consumer's max_deliver allows is the exception, because NATS redelivers nothing after it, so its retry has to go out as a copy. To tell which delivery is the last, the transport asks the consumer for its own max_deliver. Up to 5.11.0, a request that got no answer within request_timeout, or that failed on the connection, made the send of the retry fail, and that stopped messenger:consume.
To get a consumer info request with no answer on demand, we put the project's own consumer-info-proxy.php from the repository at v5.12.0 next to the script, unchanged. It forwards every byte between the worker and the server and drops only requests to $JS.API.CONSUMER.INFO.. The script starts it, sends one message whose handler always fails, and runs Symfony's Worker with its retry and failure-transport listeners, max_retries 3 and max_deliver 2. A loop stands in for a supervisor and restarts a worker that stops, up to three runs:
<?php
// retry_via: nak when the consumer info read gets no answer (#127). The repo's
// consumer-info-proxy.php sits between the worker and the server and drops every
// $JS.API.CONSUMER.INFO request. One message that always fails, max_retries 3,
// max_deliver 2. A supervisor loop restarts a worker that stops, up to three runs.
// Run: php consumer-info.php (needs the server of ../inbox-prefix/compose.yaml)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Psr\Container\ContainerInterface;
use Psr\Log\AbstractLogger;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\EventListener\SendFailedMessageForRetryListener;
use Symfony\Component\Messenger\EventListener\SendFailedMessageToFailureTransportListener;
use Symfony\Component\Messenger\EventListener\StopWorkerOnTimeLimitListener;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
use Symfony\Component\Messenger\Retry\MultiplierRetryStrategy;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
use Symfony\Component\Messenger\Worker;
final class OrderPlaced
{
public function __construct(public readonly int $order)
{
}
}
/** The service locator Symfony's listeners take, holding one service. */
final class One implements ContainerInterface
{
public function __construct(private readonly object $service)
{
}
public function get(string $id): object
{
return $this->service;
}
public function has(string $id): bool
{
return true;
}
}
/** Prints the transport's warnings. */
final class Warnings extends AbstractLogger
{
public function log($level, string|\Stringable $message, array $context = []): void
{
if ($level === 'warning') {
echo ' ', wordwrap("warning: $message", 84, "\n ", true), "\n";
}
}
}
function short(Throwable $e): string
{
return (new ReflectionClass($e))->getShortName() . ': ' . $e->getMessage();
}
$server = 'nats-jetstream://admin:[email protected]:14781';
$client = (new NatsTransportConfigurationBuilder())->build("$server/x/x")->client;
$client->connect()->await();
foreach (['orders', 'failed'] as $stream) {
try {
$client->jetStream()->deleteStream($stream)->await();
} catch (Throwable) {
}
}
$serializer = new PhpSerializer();
$failure = new NatsTransport("$server/failed/failed.orders", [], $serializer);
$failure->setup();
$options = 'consumer=worker&retry_via=nak&max_deliver=2&ack_wait=2&request_timeout=1'
. '&max_batch_timeout=1';
$direct = new NatsTransport("$server/orders/orders.placed?$options", [], $serializer);
$direct->setup();
$direct->send(new Envelope(new OrderPlaced(9)));
$direct->close();
$gaveUp = $client->subscribeQueue('$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>')
->await();
$client->flush()->await();
$proxy = proc_open(
[PHP_BINARY, __DIR__ . '/consumer-info-proxy.php', '127.0.0.1:14781', '60'],
[1 => ['pipe', 'w']],
$pipes,
);
preg_match('/LISTENING (\d+)/', (string) fgets($pipes[1]), $port);
$worker = "nats-jetstream://admin:[email protected]:{$port[1]}/orders/orders.placed";
printf(
"symfony-nats-messenger %s, the worker behind the proxy\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
);
$runs = 0;
$bus = new MessageBus([new HandleMessageMiddleware(new HandlersLocator([
OrderPlaced::class => [function (OrderPlaced $order) use (&$runs): void {
$runs++;
throw new RuntimeException("the carrier API is down (order {$order->order})");
}],
]))]);
for ($run = 1; $run <= 3; $run++) {
$transport = new NatsTransport("$worker?$options", [], $serializer, new Warnings());
$retry = new One(new MultiplierRetryStrategy(3, 100, 1));
$events = new EventDispatcher();
$events->addSubscriber(
new SendFailedMessageForRetryListener(new One($transport), $retry),
);
$events->addSubscriber(
new SendFailedMessageToFailureTransportListener(new One($failure)),
);
$events->addSubscriber(new StopWorkerOnTimeLimitListener(8));
try {
(new Worker(['orders' => $transport], $bus, $events))->run(['sleep' => 100000]);
echo "worker run $run: ended at its time limit\n";
break;
} catch (Throwable $e) {
$line = "worker run $run: stopped on " . short($e->getPrevious() ?? $e);
echo wordwrap($line, 86, "\n ", true), "\n";
} finally {
$transport->close();
}
}
proc_terminate($proxy);
$gaveUp->setTimeout(0.5);
$advisories = 0;
while ($gaveUp->next() !== null) {
$advisories++;
}
$stored = fn (string $stream): int
=> $client->jetStream()->getStream($stream)->await()->raw['state']['messages'];
$consumer = $client->jetStream()->getConsumer('orders', 'worker')->await()->raw;
$left = $consumer['num_pending'] + $consumer['num_ack_pending'];
printf("handler runs: %d\n", $runs);
printf("copies in the failure transport: %d\n", $stored('failed'));
printf("MAX_DELIVERIES advisories: %d\n", $advisories);
printf("left for the worker: %d\n", $left);
$failure->close();
$client->disconnect()->await();
On 5.11.0 (php consumer-info.php):
symfony-nats-messenger v5.11.0, the worker behind the proxy
worker run 1: stopped on TimeoutException: Request timed out for subject
$JS.API.CONSUMER.INFO.orders.worker
worker run 2: stopped on TimeoutException: Request timed out for subject
$JS.API.CONSUMER.INFO.orders.worker
worker run 3: ended at its time limit
handler runs: 2
copies in the failure transport: 0
MAX_DELIVERIES advisories: 1
left for the worker: 0
The first retry asked for the consumer's max_deliver, got no answer, and the worker stopped. Restarted, it got the second delivery, the last one the consumer allows, and stopped the same way. NATS then gave up on the message, with a MAX_DELIVERIES advisory, and nothing reached the failure transport: two handler runs out of the four Symfony was configured to make, and the message is gone.
On 5.11.1:
symfony-nats-messenger v5.11.1, the worker behind the proxy
warning: retry_via=nak on stream "orders": consumer "worker" could not be read for
its max_deliver (Request timed out for subject $JS.API.CONSUMER.INFO.orders.worker),
so the max_deliver option (2) tells which delivery is the last one. It is asked
again at the next retry.
warning: retry_via=nak on stream "orders", subject "orders.placed": the retry of the
last delivery the consumer allows was published as a copy at once, without its delay
of 94 ms. NATS redelivers nothing after that delivery, so no NAK can carry this
retry. scheduled_messages: true (NATS 2.12+, not on an interest stream) makes the
copy wait, and a max_deliver above the retries Symfony makes keeps it from being
needed.
worker run 1: ended at its time limit
handler runs: 4
copies in the failure transport: 1
MAX_DELIVERIES advisories: 0
left for the worker: 0
A read that fails on the connection or times out now decides as a JetStream error already did: the value read before, or the max_deliver option when there is none, tells which delivery is the last, with one warning, and the next retry asks again. One worker run, four handler runs, one copy in the failure transport. The second warning dates from 5.10.0: the copy of the last delivery goes out without Symfony's delay, and the warning names two ways to avoid it. 5.12.0 gives the same result.
Smaller changes
The rest of 5.12.0 is tests and CI, and none of it changes the transport:
- The functional test app now runs the same client release as the unit tests, even when a client release comes out in the middle of a CI run (#185).
- The Behat step that starts the external signing service finds its "listening on" line even when the output arrives split in chunks (#188).
- A cluster example that fails in CI says why, with how each server sees the cluster and the end of its log (#180).
- The scripted lame-duck test follows client 2.37.1, which stays on a server until that server closes the connection (#191).
5.11.1 also added a README section, "Permissions a Worker Needs", that lists every subject a worker's user needs: the pull subject, the acknowledgement subjects in both forms NATS uses, the retry topics, consumer and stream info, the management API with auto_setup, and what a NATS failure transport's own user needs. It also documents what a custom serializer's decode() must throw (#126), pins with tests that each warning is logged once per transport object (#129), and cancels a pull request's CI run when a newer commit replaces it (#170).
Upgrading
composer update idct/symfony-nats-messenger
That also brings php-nats-jetstream-client 2.39.1 or later, which 5.12.0 requires. Then:
- Without
inbox_prefixnothing changes. The client keeps_INBOX. - From 5.11.0, a worker whose user may not pull stops with an error that names the subject to grant, where it used to idle. If one of yours has been idling for that reason, expect the alert.
- With
retry_via: nak, a consumer read that times out or fails on the connection logs a warning instead of stopping the worker. - To take a worker off
_INBOX.>, add<prefix>.>to its user's subscribe grant, deploy the option (and one for a NATS failure transport limited the same way), then remove_INBOX.>. The README's "Upgrading from 5.11.1" section has the short version.
How it is tested
The README now counts 1710 unit tests at about 99.8% coverage, and docs/TESTS.md records a mutation score of 98.6%: 2001 of 2030 mutants killed on main on 29 November. For inbox_prefix, InboxPrefixTest checks what the builder hands to the client and what it refuses, and runs the real client against a scripted server that sees every inbox under the prefix. The Behat feature nats_inbox_prefix.feature sets up, sends, consumes, acknowledges and counts on a live server as a user whose only subscribe grant is own_inbox.>, and checks that the same user's send fails naming _INBOX.> without the option. The project's own example, examples/inbox-prefix.php, does the same through the transport directly.
Get it
- Source and issues: symfony-nats-messenger on GitHub, with the v5.12.0 release notes.
- Install:
composer require idct/symfony-nats-messenger, from Packagist. - Our symfony-nats-messenger software page lists what it does and what it needs.