symfony-nats-messenger 5.11: .creds logins and leaf nodes
(php, symfony, nats, release-notes) 30 min read by Bartosz Pachołek
5.11.0 logs in from a .creds file it rereads on every connect, keeps NKey seeds out of PHP with nonce_signer, reaches a hub's JetStream from a leaf node, and stops one handler's failure from deciding for all in nats mode. Plus 5.9 and 5.10.
symfony-nats-messenger 5.11.0 is out. The Symfony Messenger transport for NATS JetStream can now log in from a .creds file that it reads again on every connect, keep an NKey seed out of the PHP process altogether, and run on a NATS leaf node against the JetStream of its hub. It also fixes a nats mode bug in which the order of a message's handlers decided whether a failed message was retried or dropped.
Four releases came out between our symfony-nats-messenger 5.8 post and this one: 5.9.0, 5.9.1, 5.10.0 and 5.10.1. This post covers all five, 5.11.0 first. We ran every example below on PHP 8.5.9 against nats-server 2.15.1 in Docker, with Symfony Messenger 8.2.0 and php-nats-jetstream-client 2.36.1. Where a release changed behaviour, we installed 5.10.1 and 5.11.0 side by side from Packagist with the same dependencies, so only the transport differs, and pasted both outputs as they came out.

What 5.11 is for
Three kinds of deployment were harder than they should be:
- Locked-down logins. Short-lived JWTs that a rotation job renews, and NKey seeds that live in a KMS, an HSM, Vault or a sidecar instead of an environment variable. Up to 5.10.1 the transport took a JWT and its seed as fixed values, so a new JWT meant restarting the workers, and the seed had to be in PHP.
- Edge sites. A PHP service next to a NATS leaf node, with JetStream running only on the hub. Up to 5.10.1 every JetStream request of the transport went to
$JS.API., where nothing answers on such a leaf node. - Several handlers for one message in nats mode. Whether a failed message came back or was dropped depended on which handler the container happened to register first.
5.11.0 answers each with a new option or a fix, and adds a smaller fix for anyone who labels the transport's consumer with other tools.
Upgrading
composer update idct/symfony-nats-messenger
5.11.0 requires idct/php-nats-jetstream-client 2.34.0 or later and declares psr/container, which a Symfony application has installed already. Then check four things:
- Nats mode without the bundle. The fix for several handlers needs a new event subscriber,
AddUnrecoverableFailureStampListener. The bundle registers it. An application that leaves the bundle out registers it with thekernel.event_subscribertag, and a worker built by hand adds it to its dispatcher, as the proof of concept below does. - Log alerts on the old wording. A
jwtornkeywithout a signer is still refused, now with "The jwt option needs a signer, from nkey_seed or nonce_signer" in place of "needs nkey_seed". - A positive
nak_delaywithretry_handler: symfonynow logs a warning once per worker. It never had an effect in that mode. - Another bundle that autoconfigures
IDCT\NATS\Auth\NonceSignerInterfacein its extension makes the container fail to build, because this bundle now autoconfigures that interface too.
Coming from 5.8.x, read the 5.9 and 5.10 notes near the end of this post as well. The one most likely to bite: an option the transport does not know is now refused instead of ignored. The README has an "Upgrading from" section for every release in between.
Proof of concept: one message, two handlers
In nats mode NATS decides about retries: the transport NAKs a failed delivery for NATS to redeliver, and TERMs one that can never succeed. Since 5.10.0, "can never succeed" includes a failure Symfony marks as unrecoverable. The trouble starts when a message has two handlers. Symfony wraps both failures in one HandlerFailedException, and 5.10 read the failure from Symfony's ErrorDetailsStamp, which names only the first one. Issue #125 spells it out:

The proof of concept reproduces it with Symfony's own Worker, wired as messenger:consume wires it, with max_retries: 0 as nats mode asks for. One message, InvoicePaid, has two handlers: billing fails for good with an UnrecoverableMessageHandlingException, and mailer fails once with a timeout and succeeds on the next try. A second connection subscribes to the consumer's JetStream advisories, so the output shows what the transport told the server, not what we assume it told it.
The project is three files. The server:
services:
nats:
image: nats:2.15-alpine
command: ["-js"]
ports: ["14751:4222"]
The dependencies:
{
"require": {
"idct/symfony-nats-messenger": "^5.11",
"symfony/event-dispatcher": "^7.3 || ^8.0"
}
}
And the script:
<?php
// One message, two handlers, nats mode (retry_handler=nats, max_retries 0), run through
// Symfony's own Worker. "billing" fails for good, "mailer" fails once. Both orders.
// Run: php two-handlers.php (needs the server of compose.yaml)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NatsMessenger\EventListener\AddUnrecoverableFailureStampListener;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\EventListener\AddErrorDetailsStampListener;
use Symfony\Component\Messenger\EventListener\SendFailedMessageForRetryListener;
use Symfony\Component\Messenger\EventListener\StopWorkerOnTimeLimitListener;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
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 InvoicePaid
{
public function __construct(public readonly int $invoice)
{
}
}
/** The service locator Symfony's retry listener takes, 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;
}
}
const SERVER = 'nats-jetstream://127.0.0.1:14751';
function run(array $order): void
{
$stream = 'invoices_' . bin2hex(random_bytes(2));
$dsn = SERVER . "/$stream/$stream.paid?retry_handler=nats&max_deliver=3";
$options = ['max_batch_timeout' => 0.2];
$transport = new NatsTransport($dsn, $options, new PhpSerializer());
$transport->setup();
// A second connection watches what the transport tells JetStream about the message.
$watch = (new NatsTransportConfigurationBuilder())->build($dsn)->client;
$watch->connect()->await();
$subject = '$JS.EVENT.ADVISORY.CONSUMER.*.' . $stream . '.client';
$advisories = $watch->subscribeQueue($subject)->await();
$watch->flush()->await();
$transport->send(new Envelope(new InvoicePaid(7)));
$runs = ['billing' => 0, 'mailer' => 0];
$handlers = [
'billing' => function () use (&$runs): void {
$runs['billing']++;
throw new UnrecoverableMessageHandlingException('invoice 7 does not exist');
},
'mailer' => function () use (&$runs): void {
if (++$runs['mailer'] === 1) {
throw new RuntimeException('SMTP timeout');
}
},
];
$descriptors = [];
foreach ($order as $name) {
$descriptors[] = new HandlerDescriptor($handlers[$name], ['alias' => $name]);
}
$locator = new HandlersLocator([InvoicePaid::class => $descriptors]);
$bus = new MessageBus([new HandleMessageMiddleware($locator)]);
// What messenger:consume wires up, with max_retries 0 as nats mode asks for.
$events = new EventDispatcher();
$events->addSubscriber(new AddErrorDetailsStampListener());
$retry = new One(new MultiplierRetryStrategy(0));
$senders = new One($transport);
$events->addSubscriber(new SendFailedMessageForRetryListener($senders, $retry));
if (class_exists(AddUnrecoverableFailureStampListener::class)) {
// New in 5.11.0. The bundle registers it; a worker built by hand adds it.
$events->addSubscriber(new AddUnrecoverableFailureStampListener());
}
$events->addSubscriber(new StopWorkerOnTimeLimitListener(3));
(new Worker(['nats' => $transport], $bus, $events))->run(['sleep' => 100000]);
$seen = [];
$advisories->setTimeout(0.5);
while (($advisory = $advisories->next()) !== null) {
$kind = explode('.', $advisory->subject)[4];
if (in_array($kind, ['MSG_NAKED', 'MSG_TERMINATED', 'MAX_DELIVERIES'], true)) {
$seen[] = $kind;
}
}
$consumer = $watch->jetStream()->getConsumer($stream, 'client')->await()->raw;
printf("handlers in the order %s\n", implode(', ', $order));
printf(" JetStream got: %s\n", implode(', then ', $seen));
printf(
" billing ran %d, mailer ran %d, messages left: %d\n",
$runs['billing'],
$runs['mailer'],
$consumer['num_ack_pending'] + $consumer['num_pending'],
);
$watch->jetStream()->deleteStream($stream)->await();
$watch->disconnect()->await();
$transport->close();
}
printf(
"symfony-nats-messenger %s, Symfony Messenger %s\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
InstalledVersions::getPrettyVersion('symfony/messenger'),
);
run(['billing', 'mailer']);
run(['mailer', 'billing']);
Run it:
docker compose up --detach
composer install
php two-handlers.php
On 5.10.1 (after composer require idct/symfony-nats-messenger:5.10.1):
symfony-nats-messenger v5.10.1, Symfony Messenger v8.2.0
handlers in the order billing, mailer
JetStream got: MSG_TERMINATED
billing ran 1, mailer ran 1, messages left: 0
handlers in the order mailer, billing
JetStream got: MSG_NAKED, then MSG_TERMINATED
billing ran 2, mailer ran 2, messages left: 0
With billing first, the message was TERMed after one run of each handler. The mailer's timeout, which a second try would have cured, was never retried: the payment confirmation never went out, and nothing failed loudly. Swap the two handlers and the same two failures get a NAK, a second delivery, and a TERM once only the unrecoverable failure is left. Nobody picks the handler order on purpose; it is the order in which the container registered them.
On 5.11.0:
symfony-nats-messenger v5.11.0, Symfony Messenger v8.2.0
handlers in the order billing, mailer
JetStream got: MSG_NAKED, then MSG_TERMINATED
billing ran 2, mailer ran 2, messages left: 0
handlers in the order mailer, billing
JetStream got: MSG_NAKED, then MSG_TERMINATED
billing ran 2, mailer ran 2, messages left: 0
Both orders now go the same way, by the rule Symfony's own retry listener follows: a HandlerFailedException is unrecoverable only when every exception it wraps is. A mix is NAKed, and the delivery where the unrecoverable failure is the only one left is TERMed. Failures that are all unrecoverable are still TERMed at once, and a message with one handler is settled as before.
Under the hood, the new AddUnrecoverableFailureStampListener runs at priority -101, after Symfony's retry and failure-transport listeners have taken their copies, and stamps the envelope with whether every wrapped exception is unrecoverable. The transport reads that stamp in reject(). The listener only classifies deliveries that a transport in nats mode received (get() marks them), and neither the stamp nor that marker is ever sent with the message. Without the listener the transport falls back to the 5.10 behaviour, which is why the bundle registers it for you.
A transport on a leaf node
A leaf node takes a hub's subjects to a site, a store or an edge service. When the hub runs JetStream under a domain and the leaf node has none of its own, JetStream answers a client on the leaf node only under $JS.<domain>.API.>. The new jetstream_domain option sends every JetStream API request of the transport there: the requests of messenger:setup-transports and messenger:stats, and a worker's pulls. Publishes and acknowledgements keep their own subjects. For an account that imports another account's JetStream API, jetstream_api_prefix takes the import prefix instead (for example JS.from-a.API). Setting both is refused. Both rest on the client's NatsClient::jetStream() with a domain or an API prefix, which we covered in the php-nats-jetstream-client 2.34 post.
We ran a hub and a leaf node in Docker, next to the two login servers of the following sections:
# The servers of the leaf node and login examples. Fixed host ports:
# hub 14762 JetStream under the domain "hub", and a port for leaf nodes
# leaf 14763 a leaf node of the hub, without JetStream of its own
# operator 14764 operator mode (nsc's resolver config), JetStream for "orders"
# nkey 14765 one NKey user, JetStream on
# Make the keys first (auth/gen.sh), then: docker compose up --detach
services:
hub:
image: nats:2.15-alpine
command: ["-c", "/etc/nats/hub.conf"]
volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
ports: ["14762:4222"]
leaf:
image: nats:2.15-alpine
command: ["-c", "/etc/nats/leaf.conf"]
volumes: ["./leaf.conf:/etc/nats/leaf.conf:ro"]
ports: ["14763:4222"]
depends_on: [hub]
operator:
image: nats:2.15-alpine
command: ["-c", "/etc/nats/operator.conf"]
volumes: ["./operator.conf:/etc/nats/operator.conf:ro", "./auth:/etc/nats/auth:ro"]
ports: ["14764:4222"]
nkey:
image: nats:2.15-alpine
command: ["-c", "/etc/nats/auth/nkey.conf"]
volumes: ["./auth:/etc/nats/auth:ro"]
ports: ["14765:4222"]
# hub.conf: JetStream under the domain "hub", and a port for leaf nodes.
port: 4222
server_name: hub
jetstream {
domain: hub
}
leafnodes {
port: 7422
}
# leaf.conf: a leaf node of the hub, with no JetStream of its own.
port: 4222
server_name: leaf
leafnodes {
remotes: [
{ url: "nats-leaf://hub:7422" }
]
}
The script points a transport at the leaf node, first without the option and then with it, and finally asks the hub itself where the stream is:
<?php
// A transport on a leaf node with no JetStream of its own, whose hub runs JetStream
// under the domain "hub". Run: php leaf.php (needs the servers of nats/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)
{
}
}
$stream = 'orders_' . bin2hex(random_bytes(2));
$leaf = "nats-jetstream://127.0.0.1:14763/$stream/$stream.placed";
$version = InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger');
printf("symfony-nats-messenger %s, the transport on the leaf node\n", $version);
$attempts = ['no option' => '', 'jetstream_domain=hub' => '?jetstream_domain=hub'];
foreach ($attempts as $label => $query) {
echo $label, "\n";
try {
$transport = new NatsTransport($leaf . $query, [], new PhpSerializer());
$transport->setup();
foreach ([1, 2, 3] as $order) {
$transport->send(new Envelope(new OrderPlaced($order)));
}
$count = $transport->getMessageCount();
printf(" setup, 3 sends, messenger:stats shows %d\n", $count);
$handled = 0;
while ($handled < 3 && ($batch = [...$transport->get()]) !== []) {
foreach ($batch as $envelope) {
$transport->ack($envelope);
$handled++;
}
}
$left = $transport->getMessageCount();
printf(" a worker got and acked %d, stats now %d\n", $handled, $left);
$transport->close();
} catch (Throwable $e) {
$name = (new ReflectionClass($e))->getShortName();
printf(" %s\n", wordwrap("$name: " . $e->getMessage(), 80, "\n ", true));
}
}
// Where the stream lives: ask the hub itself.
$hub = (new NatsTransportConfigurationBuilder())
->build("nats-jetstream://127.0.0.1:14762/$stream/$stream.placed")->client;
$hub->connect()->await();
try {
$state = $hub->jetStream()->getStream($stream)->await()->raw['state'];
printf("the hub has the stream, %d messages stored\n", $state['messages']);
$hub->jetStream()->deleteStream($stream)->await();
} catch (Throwable $e) {
echo "the hub has no such stream\n";
}
$hub->disconnect()->await();
On 5.10.1:
symfony-nats-messenger v5.10.1, the transport on the leaf node
no option
RuntimeException: Failed to setup NATS stream 'orders_9680': No JetStream
responder for subject $JS.API.STREAM.INFO.orders_9680 (the subject is not bound
to a stream, or JetStream is not enabled)
jetstream_domain=hub
InvalidArgumentException: Unknown option 'jetstream_domain' in the DSN query of
the NATS transport. See "Configuration Options" in the README for the options it
takes.
the hub has no such stream
On 5.11.0:
symfony-nats-messenger v5.11.0, the transport on the leaf node
no option
RuntimeException: Failed to setup NATS stream 'orders_62d9': No JetStream
responder for subject $JS.API.STREAM.INFO.orders_62d9 (the subject is not bound
to a stream, or JetStream is not enabled)
jetstream_domain=hub
setup, 3 sends, messenger:stats shows 3
a worker got and acked 3, stats now 0
the hub has the stream, 3 messages stored
Without the option, both releases fail the same way, as messenger:setup-transports would on such a leaf node. 5.10.1 also refuses jetstream_domain itself, since 5.10.0 refuses options it does not know. On 5.11.0 the transport sets up, counts and consumes through the leaf node, and the stream lives on the hub. The hub still stores the three messages after the acks because the stream has the server's default retention, limits; messenger:stats shows 0 because nothing is left pending for the consumer.
Two things work differently on a leaf node, and the README's new "JetStream Domains and Leaf Nodes" section describes both from runs on nats-server 2.10 to 2.15. A pull for a consumer that does not exist ends as an empty batch instead of a 503, so with auto_setup a consumer deleted while a worker runs is not created again. And the transport's version checks read the leaf node's release, not the hub's. Run messenger:setup-transports before the workers start, and keep the leaf node on the hub's release.
Logins from a .creds file that changes under a running worker
nsc generate creds writes a user's JWT and seed into one .creds file. The new creds_file option takes its path, from the options, the DSN query or %env()%, with no other credential. The transport reads the file on every connect and every reconnect, not when it is built. A rotation job that renames a new file over the old one gives the next connection the new JWT, with no restart.
The interesting moment is the JWT's expiry, when the server sends User Authentication Expired and closes the connection. The project's README says a live run through an expiry is not in its test suite, because it needs a key that can sign users, which the repository keeps out; it was measured by hand. We have such a key on a scratch server, so we ran it. We made an operator, an account and a user with nsc in natsio/nats-box, and gave the user a JWT that expires in a minute and a second one that lasts an hour.
The keys, for testing only:
#!/bin/sh
# Test-only keys, made with nsc in natsio/nats-box: an operator, the account "orders"
# (JetStream on) with its user "worker", the server's resolver config, and an NKey user
# for the external signer. Run once, before `docker compose up --detach`:
# docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/auth:/work" \
# natsio/nats-box:0.19.0 sh /work/gen.sh
set -eu
export HOME=/tmp XDG_DATA_HOME=/work/nsc XDG_CONFIG_HOME=/work/nsc/config
export NKEYS_PATH=/work/nsc/nkeys
cd /work
{
nsc add operator --name demo-operator --sys
nsc add account --name orders
nsc edit account --name orders --js-mem-storage 64M --js-disk-storage 256M
nsc add user --account orders --name worker
nsc generate config --mem-resolver --config-file /work/resolver.conf --force
} > /work/gen.log 2>&1
nsc generate nkey --user > /work/nkey-user.txt 2>> /work/gen.log
printf 'port: 4222\njetstream {}\nauthorization { users: [ { nkey: %s } ] }\n' \
"$(sed -n 2p /work/nkey-user.txt)" > /work/nkey.conf
echo "keys written"
The server in operator mode:
# operator.conf: operator mode, with the operator, accounts and resolver that nsc wrote.
port: 4222
server_name: operator
jetstream {
store_dir: /data
}
include auth/resolver.conf
The two JWTs of the same user:
#!/bin/sh
# Issues the JWT of the user "worker" twice, as a rotation does: short.creds expires in a
# minute, renewed.creds in an hour. Same user, same key, two JWTs. Run right before
# creds-worker.php:
# docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/auth:/work" \
# natsio/nats-box:0.19.0 sh /work/issue.sh
set -eu
export HOME=/tmp XDG_DATA_HOME=/work/nsc XDG_CONFIG_HOME=/work/nsc/config
export NKEYS_PATH=/work/nsc/nkeys
{
nsc edit user --account orders --name worker --expiry 1m
nsc generate creds --account orders --name worker > /work/short.creds
nsc edit user --account orders --name worker --expiry 1h
nsc generate creds --account orders --name worker > /work/renewed.creds
} 2> /work/issue.log
The worker runs Symfony's Worker with reconnect: true, as the README advises for a worker that runs through a rotation, and prints every line the client logs, timed from the JWT's expiry:
<?php
// A worker that logs in from a .creds file whose JWT expires while it runs.
// php creds-worker.php renew a rotation renews the file before the expiry
// php creds-worker.php keep nobody renews it
// auth/short.creds expires a minute after auth/issue.sh ran, auth/renewed.creds an
// hour after. Needs the operator-mode server of nats/compose.yaml.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NatsMessenger\NatsTransport;
use Psr\Log\AbstractLogger;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Event\WorkerRunningEvent;
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 Job
{
public function __construct(public readonly int $id)
{
}
}
const AUTH = __DIR__ . '/auth';
const LIVE = AUTH . '/live.creds';
/** A rotation: write the new file next to the old one, rename it over the old one. */
function install(string $file): void
{
copy(AUTH . '/' . $file, LIVE . '.new');
rename(LIVE . '.new', LIVE);
}
install('short.creds');
// The exp claim of the JWT in the file (the JWT is not the secret; the seed is).
preg_match('/BEGIN NATS USER JWT-+\s+(\S+)/', (string) file_get_contents(LIVE), $m);
$claims = json_decode(base64_decode(strtr(explode('.', $m[1])[1], '-_', '+/')), true);
define('EXPIRY', (float) $claims['exp']);
/** The time, in seconds from the JWT's expiry. */
function at(): string
{
return str_pad(sprintf('exp%+ds', (int) round(microtime(true) - EXPIRY)), 8);
}
final class Log extends AbstractLogger
{
public function log($level, \Stringable|string $message, array $context = []): void
{
$line = wordwrap("$level: $message", 78, "\n" . str_repeat(' ', 11));
printf("%s %s\n", at(), $line);
}
}
$mode = $argv[1] ?? 'renew';
$stream = 'jobs_' . bin2hex(random_bytes(2));
$dsn = "nats-jetstream://127.0.0.1:14764/$stream/$stream.run";
$options = ['creds_file' => LIVE, 'reconnect' => true];
$worker = new NatsTransport($dsn, $options, new PhpSerializer(), new Log());
// The sender is another process in real life; here it logs in from the hour-long file.
$sendAs = ['creds_file' => AUTH . '/renewed.creds'];
$sender = new NatsTransport($dsn, $sendAs, new PhpSerializer());
$sender->setup();
$sender->send(new Envelope(new Job(1)));
printf("%s worker starts (%s), job 1 waiting\n", at(), $mode);
$handlers = new HandlersLocator([Job::class => [function (Job $job): void {
printf("%s handled job %d\n", at(), $job->id);
}]]);
$bus = new MessageBus([new HandleMessageMiddleware($handlers)]);
$plan = ['job 2' => EXPIRY + 5];
if ($mode === 'renew') {
$plan['renew'] = EXPIRY - 30;
}
$events = new EventDispatcher();
$events->addListener(WorkerRunningEvent::class, function () use (&$plan, $sender): void {
foreach ($plan as $step => $time) {
if (microtime(true) < $time) {
continue;
}
unset($plan[$step]);
if ($step === 'renew') {
install('renewed.creds');
printf("%s the rotation renamed a new .creds file over the old one\n", at());
} else {
$sender->send(new Envelope(new Job(2)));
printf("%s job 2 sent\n", at());
}
}
});
$limit = (int) (EXPIRY + 15 - microtime(true));
$events->addSubscriber(new StopWorkerOnTimeLimitListener($limit));
try {
(new Worker(['jobs' => $worker], $bus, $events))->run(['sleep' => 200000]);
printf("%s worker stopped at its time limit\n", at());
} catch (Throwable $e) {
printf("%s worker ended: %s\n", at(), $e->getMessage());
}
printf("%s jobs waiting in the stream: %d\n", at(), $sender->getMessageCount());
$worker->close();
$sender->close();
Run:
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/auth:/work" \
natsio/nats-box:0.19.0 sh /work/issue.sh
php creds-worker.php renew
With a rotation 30 seconds before the expiry:
exp-60s worker starts (renew), job 1 waiting
exp-60s info: NATS connection Connected
exp-60s handled job 1
exp-30s the rotation renamed a new .creds file over the old one
exp+0s info: NATS connection Disconnected
exp+0s info: NATS connection Reconnected
exp+5s job 2 sent
exp+5s handled job 2
exp+14s info: NATS connection Closed
exp+14s worker stopped at its time limit
exp+14s jobs waiting in the stream: 0
The server cut the connection at the expiry, the client reconnected in the same second with the JWT the file held by then, and the worker handled job 2 five seconds later. Nothing restarted.
The same with nobody renewing the file (php creds-worker.php keep, after a fresh issue.sh):
exp-59s worker starts (keep), job 1 waiting
exp-59s info: NATS connection Connected
exp-59s handled job 1
exp+1s info: NATS connection Disconnected
exp+1s error: NATS connection error: Server rejected authentication during connect:
'User Authentication Expired'
exp+1s warning: NATS connection Closed
exp+1s worker ended: Server sent error frame: 'User Authentication Expired'
exp+1s jobs waiting in the stream: 0
The reconnect read the file again, found the expired JWT, and the server refused it. The worker stopped with the server's own reason, User Authentication Expired, which tells an operator what to fix. A supervisor would restart it into the same refusal until the file is renewed, so that message is worth an alert.
The file is also checked when the transport is built: a path that is not a readable .creds file is refused then, and no error repeats the file's text, since it holds the seed. creds_file needs the sodium extension, as nkey_seed does.
The seed in another process: nonce_signer
A .creds file still puts the seed on the PHP host. For teams that keep keys in a KMS, an HSM, Vault or a sidecar, nonce_signer names a service of the application that implements the client's IDCT\NATS\Auth\NonceSignerInterface and signs the server's nonce however it likes. Next to it, nkey holds the user's public key, or jwt the user's JWT. The bundle autoconfigures the interface with the tag idct_nats_messenger.nonce_signer and hands the transport factory a locator of those services, so each transport can name its own signer.
Our signing process holds the seed and answers one nonce per TCP connection:
<?php
// The signing process: it holds the NKey seed and signs the nonces it is sent, one
// per connection, as a sidecar, a KMS or Vault's transit engine would. The seed comes
// on stdin. Started by signer-login.php.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Auth\NkeySeedSigner;
$signer = new NkeySeedSigner(trim((string) stream_get_contents(STDIN)));
$server = stream_socket_server('tcp://127.0.0.1:0');
$address = (string) stream_socket_get_name($server, false);
echo 'listening on ', substr($address, strrpos($address, ':') + 1), "\n";
$deadline = time() + 60;
while (time() < $deadline) {
$connection = @stream_socket_accept($server, 1);
if ($connection === false) {
continue;
}
$nonce = rtrim((string) fgets($connection), "\r\n");
fwrite($connection, $signer->sign($nonce) . "\n");
fclose($connection);
}
The transport's process starts it, keeps only the public key, and builds the transport with the kind of locator the bundle builds:
<?php
// An NKey login whose seed stays in another process: the transport has the public key
// in `nkey` and the id of a signer service in `nonce_signer`.
// Run: php signer-login.php (needs the nkey server of nats/compose.yaml)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NATS\Auth\NonceSignerInterface;
use IDCT\NatsMessenger\NatsTransport;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
/** The application's signer service: it asks the signing process for each signature. */
final class SidecarSigner implements NonceSignerInterface
{
public int $signed = 0;
public function __construct(private readonly string $address)
{
}
public function sign(string $nonce): string
{
$connection = stream_socket_client($this->address, timeout: 1.0);
fwrite($connection, $nonce . "\n");
$signature = trim((string) fgets($connection));
fclose($connection);
$this->signed++;
return $signature;
}
}
// Start the signing process and hand it the seed; this one keeps the public key only.
[$seed, $public] = file(__DIR__ . '/auth/nkey-user.txt', FILE_IGNORE_NEW_LINES);
$pipes = [];
$command = [PHP_BINARY, __DIR__ . '/signer.php'];
$process = proc_open($command, [['pipe', 'r'], ['pipe', 'w']], $pipes);
fwrite($pipes[0], $seed);
fclose($pipes[0]);
unset($seed);
preg_match('/listening on (\d+)/', (string) fgets($pipes[1]), $port);
$signer = new SidecarSigner('tcp://127.0.0.1:' . $port[1]);
// What the bundle builds from the services tagged idct_nats_messenger.nonce_signer.
$signers = new ServiceLocator(['app.nats_signer' => fn () => $signer]);
$options = ['nkey' => $public, 'nonce_signer' => 'app.nats_signer'];
printf(
"symfony-nats-messenger %s\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
);
$stream = 'signed_' . bin2hex(random_bytes(2));
$dsn = "nats-jetstream://127.0.0.1:14765/$stream/$stream.jobs";
try {
$transport = new NatsTransport($dsn, $options, new PhpSerializer(), null, $signers);
$transport->setup();
$transport->send(new Envelope(new ArrayObject(['job' => 1])));
$got = [...$transport->get()];
$transport->ack($got[0]);
printf("logged in as %s...\n", substr($public, 0, 12));
printf(
"setup, send, get, ack: %d message, %d signature(s) from the other process\n",
count($got),
$signer->signed,
);
$transport->close();
} catch (Throwable $e) {
printf("%s: %s\n", (new ReflectionClass($e))->getShortName(), $e->getMessage());
}
// Refused when the transport is built, before any connection.
$mistakes = [
['nonce_signer' => 'app.nats_signer'],
['nonce_signer' => 'app.nope'] + $options,
];
foreach ($mistakes as $bad) {
try {
new NatsTransport($dsn, $bad, new PhpSerializer(), null, $signers);
} catch (Throwable $e) {
printf("refused: %s\n", wordwrap($e->getMessage(), 78, "\n "));
}
}
proc_terminate($process);
symfony-nats-messenger v5.11.0
logged in as UARFGQCCAIJO...
setup, send, get, ack: 1 message, 1 signature(s) from the other process
refused: The nonce_signer option needs nkey or jwt: the client signs the server's nonce
only for an NKey or a JWT login, so with neither it would send no credentials,
and the connection would log in as the server's no_auth_user or anonymously.
Put the public key of the signer's user (U...) in nkey, or the user's JWT in
jwt.
refused: The nonce_signer option names the service 'app.nope', which is not one of the
services tagged idct_nats_messenger.nonce_signer. A service that implements
IDCT\NATS\Auth\NonceSignerInterface gets the tag when it is autoconfigured;
give it the tag by hand otherwise.
One connection, one signature, made in the other process. Mistakes fail when the transport is built, before anything connects: a signer with neither nkey nor jwt, which would log in as the server's no_auth_user or anonymously, and a service id that no tagged service has. Keep the signer fast: it has to answer within the server's authorization timeout, 2 seconds by default, and the PHP process waits for it.
setup() keeps the labels of a durable consumer
setup() runs on every messenger:setup-transports and, with auto_setup, at the first send or get of a process. It sent a consumer configuration built from the transport's options alone, and NATS takes that as an update that replaces the whole stored configuration. So metadata or a description that another tool put on the consumer, such as nats consumer edit or an operator's label, was wiped on every deploy.
<?php
// Another tool labels the transport's durable consumer, then setup() runs again, as
// messenger:setup-transports or auto_setup does on every deploy.
// Run: php labels.php (needs the server of two-handlers/compose.yaml)
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
/** The consumer's metadata (without the server's own _nats. entries) and description. */
function labels(NatsClient $client, string $stream): string
{
$info = $client->jetStream()->getConsumer($stream, 'client')->await();
$config = $info->raw['config'];
$mine = array_filter(
$config['metadata'] ?? [],
fn (string $key): bool => !str_starts_with($key, '_nats.'),
ARRAY_FILTER_USE_KEY,
);
return sprintf(
"\n metadata %s\n description %s",
json_encode($mine === [] ? new stdClass() : $mine),
json_encode($config['description'] ?? null),
);
}
$stream = 'billing_' . bin2hex(random_bytes(2));
$dsn = "nats-jetstream://127.0.0.1:14751/$stream/$stream.jobs";
printf(
"symfony-nats-messenger %s\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
);
$transport = new NatsTransport($dsn, [], new PhpSerializer());
$transport->setup();
// What `nats consumer edit` or an operator's script does: the same config, plus labels.
$client = (new NatsTransportConfigurationBuilder())->build($dsn)->client;
$client->connect()->await();
$config = $client->jetStream()->getConsumer($stream, 'client')->await()->raw['config'];
$config['metadata'] = ($config['metadata'] ?? []) + ['owner' => 'team-billing'];
$config['description'] = 'billing jobs, page the on-call';
$update = json_encode(['stream_name' => $stream, 'config' => $config]);
$client->request('$JS.API.CONSUMER.CREATE.' . $stream . '.client', $update)->await();
printf("labelled by another tool:%s\n", labels($client, $stream));
$transport->setup();
printf("after setup() again:%s\n", labels($client, $stream));
$transport->close();
$client->jetStream()->deleteStream($stream)->await();
$client->disconnect()->await();
On 5.10.1:
symfony-nats-messenger v5.10.1
labelled by another tool:
metadata {"owner":"team-billing"}
description "billing jobs, page the on-call"
after setup() again:
metadata {}
description null
On 5.11.0:
symfony-nats-messenger v5.11.0
labelled by another tool:
metadata {"owner":"team-billing"}
description "billing jobs, page the on-call"
after setup() again:
metadata {"owner":"team-billing"}
description "billing jobs, page the on-call"
5.11.0 reads the live consumer, which it already looked up for the replay policy, and sends its metadata and description back with the update. One gap stays, and the changelog says so: an entry written between that lookup and the update is still lost, because the consumer API has no conditional update.
Smaller changes in 5.11
get()declares Messenger's fetch size (#150). Messenger 8.1 added a$fetchSizehint toReceiverInterface::get(), and Symfony'sDebugClassLoaderreported a deprecation in the dev environment. The parameter is now declared in a comment, as Messenger's own interface declares it until Symfony 9. The size of a pull is still decided bybatching.- Symfony Messenger 8.1.12 and 8.2 (#140, #141, #149, #154). The tests and docs follow two Worker changes: from 8.1.12 the Worker reads a whole pull before it handles the first message, so a keepalive covers the waiting messages too, and from 7.4.24 and 8.1.12 it calls
close()when it stops. What aDispatchOnFailureStamp, new in 8.2, does in nats mode is pinned by a test. - nats-server 2.14.10 and 2.15.3 close client connections before they stop JetStream, so on those releases a stopping server gives a pull no 503 (#157). Nothing changes in the transport; the docs name the releases.
- Every retry path has a Behat scenario on a real server and an example (#123).
The warning for a nak_delay that does nothing (#117) and the new wording of the refusals are what an upgrade may add to your logs. This script shows them, together with the typo check of 5.10.0:
<?php
// Three configurations whose handling changed between 5.9 and 5.11. The second runs
// setup() on the server of two-handlers/compose.yaml. Run: php upgrade-check.php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NatsMessenger\NatsTransport;
use Psr\Log\AbstractLogger;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
final class Log extends AbstractLogger
{
public function log($level, \Stringable|string $message, array $context = []): void
{
printf(" logged %s: %s\n", $level, wordwrap((string) $message, 64, "\n "));
}
}
printf(
"symfony-nats-messenger %s\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
);
$stream = 'check_' . bin2hex(random_bytes(2));
$dsn = "nats-jetstream://127.0.0.1:14751/$stream/$stream.jobs";
$cases = [
'a typo: max_delivers=5' => [$dsn . '?max_delivers=5', []],
'nak_delay=2 in symfony mode, then setup()' => [$dsn . '?nak_delay=2', []],
'a jwt with no seed or signer' => [$dsn, ['jwt' => 'eyJ0.eyJ1.c2ln']],
];
foreach ($cases as $label => [$url, $options]) {
echo $label, "\n";
try {
$transport = new NatsTransport($url, $options, new PhpSerializer(), new Log());
$transport->setup();
echo " setup() ran\n";
$transport->close();
} catch (Throwable $e) {
printf(" refused: %s\n", wordwrap($e->getMessage(), 76, "\n "));
}
}
symfony-nats-messenger v5.11.0
a typo: max_delivers=5
refused: Unknown option 'max_delivers' in the DSN query of the NATS transport. Did
you mean 'max_deliver'?
nak_delay=2 in symfony mode, then setup()
logged info: NATS connection Connected
logged warning: nak_delay=2 on stream "check_b5ba", subject "check_b5ba.jobs"
has no effect with retry_handler: symfony: the transport TERMs a
failed message, and Symfony's retry strategy times its retry.
Remove nak_delay, or use retry_handler: nats.
setup() ran
logged info: NATS connection Closed
a jwt with no seed or signer
refused: The jwt option needs a signer, from nkey_seed or nonce_signer: the client
signs the server's nonce with the key of the JWT's user and cannot connect
without one. Put that user's seed (SU...) in nkey_seed, as a .creds file
holds both values, or name a service that signs the nonce in nonce_signer.
On 5.10.1 the same script logs no warning in the second case and words the third "The jwt option needs nkey_seed". The typo in the first case has been refused since 5.10.0.
What came between: 5.9 and 5.10
5.9.0 added retry_via: nak for symfony mode. Symfony's retry strategy still decides whether and when a failed message is retried, but NATS carries the retry out: the transport NAKs the failed delivery with Symfony's delay, to the millisecond and on any supported server, and NATS redelivers the original. It grew out of a pull request by Petar Fedorovsky (#113), which built on an issue Adrian Brajković opened (#109) about willRetry() in nats mode. Thank you both. The same release refuses scheduled_messages on a server before 2.12, where every delayed message was stored and never delivered, and stops allowing Symfony Messenger 7.2, on which the transport could not load.
5.9.1 fixed three ways to lose or loop on a message:
retry_via: nakfollows the consumer's ownmax_deliverinstead of the option's, so the retry of the last delivery is no longer NAKed into nothing.scheduled_messagesis refused on an interest stream where nothing has interest in the delayed subjects, which dropped every delayed message.- Nats mode TERMs a message that cannot be decoded. NATS used to bring it back for ever: two workers of 3 seconds got one such message 3769 times on Messenger 8.1.9.
5.10.0 made the two retry modes plain. In symfony mode Symfony decides and its failure transport keeps what it gives up on. In nats mode NATS decides, and a failure Symfony marks as unrecoverable is TERMed instead of being run on every delivery max_deliver allows. An option the transport does not know is refused with a suggestion, as the first case above shows; up to 5.9.x a typo silently left the default in place. A message that cannot be decoded is handled as Symfony's own transports handle it, and only a MessageDecodingFailedException counts as one: any other serializer exception leaves the message for redelivery. New warnings say when a retry goes out without its delay, and when NATS deletes from a stream what max_deliver stops.
5.10.1 gave the application back its own warnings during unserialize (a __wakeup() or an autoloader), which 5.10.0 had turned into decode failures that TERMed the message. With reconnect: true, a worker whose user may pull but not ask for consumer info no longer sits through a whole reconnect inside get(), deaf to messenger:stop-workers and SIGTERM.
How it is tested
The README now counts 1672 unit tests at about 99.8% coverage, and the mutation gate kills 1998 of 2026 mutants (98.6% MSI). Behat scenarios run against live NATS servers, among them the new leaf node and two-handler scenarios. The README's "Tested by" notes also say what the suite does not cover; the JWT expiry above was one of those gaps.
Get it
- Source and issues: symfony-nats-messenger on GitHub, with the v5.11.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.