skip to content
szczecin 53.43N 14.55E ./start-project

symfony-nats-messenger 5.13: delayed messages on leaf nodes

(php, symfony, nats, release-notes) 25 min read by Bartosz Pachołek

5.13.0 decides scheduled_messages by the API level of the JetStream it uses, not the leaf node's release: an old leaf node now schedules through its hub, a new one in front of an old hub is refused before it writes. Plus 5.12.1 and 5.12.2, run on a cluster.

symfony-nats-messenger 5.13.0 is out, with one fix that changes what the transport asks the server. With scheduled_messages, the transport has to know whether the JetStream that holds its stream can schedule messages. Up to 5.12.2 it went by the release of the server it was connected to. On a leaf node that is the wrong server: the stream lives on the hub. 5.13.0 asks the JetStream it actually uses for its API level, so an old leaf node in front of a new hub now sends delayed messages, and a new leaf node in front of an old hub is refused before it writes anything.

Our last post covered symfony-nats-messenger 5.12, so this one also covers two patch releases: 5.12.1, whose warning about an unreadable consumer now names the subject to grant under a JetStream domain, and 5.12.2, where a change of the consumer's leader in a cluster no longer ends a worker. We ran every example on PHP 8.5.9 against the official NATS images in Docker, with Symfony Messenger 8.2.0 and php-nats-jetstream-client 2.42.1. We installed 5.12.0, 5.12.1, 5.12.2 and 5.13.0 from Packagist side by side with the same composer.lock, so only the transport differs. The outputs are pasted as they came out.

GitHub release page of symfony-nats-messenger v5.13.0: scheduled_messages follows the JetStream API level of the hub, not the leaf node's release

What 5.13 is for

Message schedules arrived in NATS 2.12. An older server does not refuse them: it accepts a stream with allow_msg_schedules, ignores the setting, and stores a scheduled message on its delayed subject, where it stays and is never delivered. Since 5.9.0 the transport refuses scheduled_messages where schedules do not exist, at setup() and at the send of a delayed message, instead of losing those messages, Symfony's delayed retries among them. To decide, it read the version in the INFO line of the server it was connected to.

Since 5.11.0 the transport also works on a leaf node with no JetStream of its own: with jetstream_domain, its JetStream API requests go to $JS.<domain>.API., the leaf node forwards them, and the stream and its consumer live on the hub (our symfony-nats-messenger 5.11 post shows it). Put those two together and the version check reads the leaf node's release, which says nothing about the hub. That goes wrong both ways:

  • A leaf node before 2.12 in front of a hub of 2.12 or later refused the setup and every delayed send, although the hub schedules and delivers them.
  • A leaf node of 2.12 or later in front of an older hub passed the check. The setup wrote the stream, then failed once the client saw that the hub had ignored allow_msg_schedules, and every delayed message sent afterwards was stored on the hub and never delivered.

NATS has an answer for this in ADR-44: JetStream reports an API level in its account info, and clients check that level instead of a server version. php-nats-jetstream-client reads it since 2.37.0 (accountInfo()->apiLevel; none before 2.11, 1 on 2.11.17, 3 on 2.12.15, 4 on 2.14.10, per its changelog), which our php-nats-jetstream-client 2.37 post covers. 5.13.0 uses it: setup() and the send of a delayed message ask the JetStream the transport uses for its level, once per connection, under jetstream_domain or jetstream_api_prefix when one is set. Level 2 or more has message schedules. In a cluster, the meta leader answers.

Proof of concept: two hubs, two leaf nodes

Two hubs run JetStream under the domain hub, one on nats-server 2.15.3 and one on 2.11.17. Each has a leaf node of the other release in front of it:

yaml
# Two hubs, each with a leaf node of the other release in front of it. Host ports:
#   hub-215   14791  nats-server 2.15.3, JetStream under the domain "hub"
#   leaf-211  14792  nats-server 2.11.17, leaf node of hub-215, no JetStream
#   hub-211   14793  nats-server 2.11.17, JetStream under the domain "hub"
#   leaf-215  14794  nats-server 2.15.3, leaf node of hub-211, no JetStream
services:
  hub-215:
    image: nats:2.15.3-alpine
    command: ["-c", "/etc/nats/hub.conf", "--server_name", "hub-215"]
    volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
    ports: ["14791:4222"]
  leaf-211:
    image: nats:2.11.17-alpine
    command: ["-c", "/etc/nats/leaf.conf", "--server_name", "leaf-211"]
    environment: { HUB: "nats-leaf://hub-215:7422" }
    volumes: ["./leaf.conf:/etc/nats/leaf.conf:ro"]
    ports: ["14792:4222"]
    depends_on: [hub-215]
  hub-211:
    image: nats:2.11.17-alpine
    command: ["-c", "/etc/nats/hub.conf", "--server_name", "hub-211"]
    volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
    ports: ["14793:4222"]
  leaf-215:
    image: nats:2.15.3-alpine
    command: ["-c", "/etc/nats/leaf.conf", "--server_name", "leaf-215"]
    environment: { HUB: "nats-leaf://hub-211:7422" }
    volumes: ["./leaf.conf:/etc/nats/leaf.conf:ro"]
    ports: ["14794:4222"]
    depends_on: [hub-211]
text
# hub.conf: JetStream under the domain "hub", and a port for leaf nodes.
port: 4222

jetstream {
  domain: hub
  store_dir: "/data"
}

leafnodes {
  port: 7422
}

The leaf nodes have no jetstream block, and three users for a local test only. app may do anything, nolevel may not ask the hub's JetStream for its level, and noread is for the 5.12.1 section below:

text
# leaf.conf: a leaf node of the hub in $HUB, with no JetStream of its own.
# For a local test only: each password is the user name.
port: 4222

leafnodes {
  remotes: [
    { url: $HUB }
  ]
}

authorization {
  users = [
    # The application's user: may do anything.
    { user: app, password: app }
    # Anything but asking the hub's JetStream for its API level.
    { user: nolevel, password: nolevel, permissions: {
      publish: { allow: ">", deny: "$JS.hub.API.INFO" }
      subscribe: ">"
    } }
    # Anything but reading the consumer "worker" of the stream "orders".
    { user: noread, password: noread, permissions: {
      publish: { allow: ">", deny: "$JS.hub.API.CONSUMER.INFO.orders.worker" }
      subscribe: ">"
    } }
  ]
}

The project needs the transport and, for the worker examples further down, Symfony's event dispatcher:

json
{
    "require": {
        "idct/symfony-nats-messenger": "^5.13",
        "symfony/event-dispatcher": "^8.2"
    }
}

The script runs three cases through a leaf node with jetstream_domain=hub&scheduled_messages=true. Each one deletes the stream on the hub, runs setup(), sends two reminders delayed by 2 seconds, waits up to 5 seconds for them, and asks the hub itself, on its own port, what it holds:

php
<?php

// scheduled_messages on a leaf node with no JetStream, through jetstream_domain: hub.
// Each case resets the hub, runs setup(), sends two messages delayed 2 s, waits for
// them, and asks the hub what it holds. Run: php schedules.php
// (needs the servers 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 Psr\Log\AbstractLogger;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Stamp\DelayStamp;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;

final class Reminder
{
    public function __construct(public readonly int $id)
    {
    }
}

/** Prints the warnings and errors the transport and its client log. */
final class Printed extends AbstractLogger
{
    public function log($level, string|\Stringable $message, array $context = []): void
    {
        if (in_array($level, ['warning', 'error'], true)) {
            echo '  ', wordwrap("$level: $message", 84, "\n    ", true), "\n";
        }
    }
}

/** Prints a failure, or only its name when the message is the one printed last. */
function report(string $what, Throwable $e): void
{
    static $last = null;
    $name = (new ReflectionClass($e))->getShortName();
    if ($e->getMessage() === $last) {
        echo "  $what: $name, the same message\n";

        return;
    }
    $last = $e->getMessage();
    echo '  ', wordwrap("$what: $name: $last", 84, "\n    ", true), "\n";
}

/** Runs $call on a connection straight to the hub on $port. */
function onTheHub(int $port, Closure $call): mixed
{
    $client = (new NatsTransportConfigurationBuilder())
        ->build("nats-jetstream://127.0.0.1:$port/x/x")->client;
    $client->connect()->await();
    try {
        return $call($client->jetStream());
    } finally {
        $client->disconnect()->await();
    }
}

function hubHolds(int $port): string
{
    return onTheHub($port, function ($jetStream): string {
        try {
            $raw = $jetStream->getStream('reminders')->await()->raw;
        } catch (Throwable) {
            return 'no stream "reminders"';
        }
        $schedules = ($raw['config']['allow_msg_schedules'] ?? false) ? 'on' : 'off';

        return sprintf('the stream, message schedules %s, %d message(s) stored',
            $schedules, $raw['state']['messages']);
    });
}

printf(
    "symfony-nats-messenger %s, php-nats-jetstream-client %s\n",
    InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
    InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client'),
);

$cases = [
    'app on leaf 2.11.17, hub 2.15.3' => ['app', 14792, 14791],
    'app on leaf 2.15.3, hub 2.11.17' => ['app', 14794, 14793],
    'nolevel on leaf 2.11.17, hub 2.15.3' => ['nolevel', 14792, 14791],
];
foreach ($cases as $label => [$user, $leaf, $hub]) {
    echo "$label\n";
    onTheHub($hub, function ($jetStream): void {
        try {
            $jetStream->deleteStream('reminders')->await();
        } catch (Throwable) {
        }
    });
    $dsn = "nats-jetstream://$user:$user@127.0.0.1:$leaf/reminders/reminders.due"
        . '?jetstream_domain=hub&scheduled_messages=true&max_batch_timeout=0.5';
    $transport = new NatsTransport($dsn, [], new PhpSerializer(), new Printed());
    try {
        $transport->setup();
        echo "  setup: done\n";
    } catch (Throwable $e) {
        report('setup', $e);
    }
    echo '  the hub has ', hubHolds($hub), "\n";

    $sentAt = microtime(true);
    foreach ([1, 2] as $id) {
        try {
            $transport->send(new Envelope(new Reminder($id), [new DelayStamp(2000)]));
            echo "  send of reminder $id, delayed 2 s: done\n";
        } catch (Throwable $e) {
            report("send of reminder $id", $e);
        }
    }
    $arrived = [];
    try {
        while (count($arrived) < 2 && microtime(true) - $sentAt < 5) {
            foreach ($transport->get() as $envelope) {
                $arrived[] = sprintf('reminder %d after %.1f s',
                    $envelope->getMessage()->id, microtime(true) - $sentAt);
                $transport->ack($envelope);
            }
        }
        $arrived = $arrived === [] ? 'nothing in 5 s' : implode(', ', $arrived);
        echo "  received: $arrived\n";
    } catch (Throwable $e) {
        report('get', $e);
    }
    echo '  the hub has ', hubHolds($hub), "\n";
    $transport->close();
}

Run it:

bash
docker compose up --detach
composer install
php schedules.php

On 5.12.2, in an install that differs only in the transport:

text
symfony-nats-messenger v5.12.2, php-nats-jetstream-client v2.42.1
app on leaf 2.11.17, hub 2.15.3
  setup: RuntimeException: The 'scheduled_messages' option requires NATS Server >=
    2.12, but the connected server reports 2.11.17. Disable scheduled_messages or
    upgrade NATS.
  the hub has no stream "reminders"
  send of reminder 1: TransportException: The 'scheduled_messages' option requires
    NATS Server >= 2.12, but the connected server reports 2.11.17. Disable
    scheduled_messages or upgrade NATS. The delayed message was not sent: this server
    would store it and never deliver it.
  send of reminder 2: TransportException, the same message
  received: nothing in 5 s
  the hub has no stream "reminders"
app on leaf 2.15.3, hub 2.11.17
  setup: RuntimeException: The 'scheduled_messages' option requires NATS Server >=
    2.12, but the connected server reports 2.15.3. Disable scheduled_messages or upgrade
    NATS.
  the hub has the stream, message schedules off, 0 message(s) stored
  send of reminder 1, delayed 2 s: done
  send of reminder 2, delayed 2 s: done
  received: nothing in 5 s
  the hub has the stream, message schedules off, 2 message(s) stored
nolevel on leaf 2.11.17, hub 2.15.3
  setup: RuntimeException: The 'scheduled_messages' option requires NATS Server >=
    2.12, but the connected server reports 2.11.17. Disable scheduled_messages or
    upgrade NATS.
  the hub has no stream "reminders"
  send of reminder 1: TransportException: The 'scheduled_messages' option requires
    NATS Server >= 2.12, but the connected server reports 2.11.17. Disable
    scheduled_messages or upgrade NATS. The delayed message was not sent: this server
    would store it and never deliver it.
  send of reminder 2: TransportException, the same message
  received: nothing in 5 s
  the hub has no stream "reminders"

The first case is a leaf node on 2.11.17 refusing what its 2.15.3 hub would do: the setup and both sends are refused, because the connected server reports 2.11.17. The second case is the dangerous one. The 2.15.3 leaf node passed the check, so the setup wrote the stream on the 2.11.17 hub, with schedules off, and then failed with a message that names 2.15.3, a release that has schedules. Both delayed sends then went through, the hub stored them, and nothing arrived. A worker would never see those messages, and nothing would tell it.

On 5.13.0:

text
symfony-nats-messenger v5.13.0, php-nats-jetstream-client v2.42.1
app on leaf 2.11.17, hub 2.15.3
  setup: done
  the hub has the stream, message schedules on, 0 message(s) stored
  send of reminder 1, delayed 2 s: done
  send of reminder 2, delayed 2 s: done
  received: reminder 1 after 2.4 s, reminder 2 after 2.4 s
  the hub has the stream, message schedules on, 2 message(s) stored
app on leaf 2.15.3, hub 2.11.17
  setup: RuntimeException: The 'scheduled_messages' option requires NATS Server >=
    2.12, but the JetStream of this account reports API level 1, and message schedules
    need API level 2. Disable scheduled_messages or upgrade NATS.
  the hub has no stream "reminders"
  send of reminder 1: TransportException: The 'scheduled_messages' option requires
    NATS Server >= 2.12, but the JetStream of this account reports API level 1, and
    message schedules need API level 2. Disable scheduled_messages or upgrade NATS. The
    delayed message was not sent: a JetStream without message schedules would store it
    and never deliver it.
  send of reminder 2: TransportException, the same message
  received: nothing in 5 s
  the hub has no stream "reminders"
nolevel on leaf 2.11.17, hub 2.15.3
  error: NATS connection error: Server sent recoverable error frame: 'Permissions
    Violation for Publish to "$JS.hub.API.INFO"'
  setup: RuntimeException: The 'scheduled_messages' option requires NATS Server >=
    2.12, but the connected server reports 2.11.17, and the JetStream API level could
    not be read (The server refused the request to "$JS.hub.API.INFO": Permissions
    Violation for Publish to "$JS.hub.API.INFO". No responder received it. Grant this
    connection's user permission to publish to "$JS.hub.API.INFO"). Disable
    scheduled_messages or upgrade NATS.
  the hub has no stream "reminders"
  send of reminder 1: TransportException: The 'scheduled_messages' option requires
    NATS Server >= 2.12, but the connected server reports 2.11.17, and the JetStream API
    level could not be read (The server refused the request to "$JS.hub.API.INFO":
    Permissions Violation for Publish to "$JS.hub.API.INFO". No responder received it.
    Grant this connection's user permission to publish to "$JS.hub.API.INFO"). Disable
    scheduled_messages or upgrade NATS. The delayed message was not sent: a JetStream
    without message schedules would store it and never deliver it.
  send of reminder 2: TransportException, the same message
  received: nothing in 5 s
  the hub has no stream "reminders"

The old leaf node now sets up a stream with schedules on, on the hub, and both reminders arrive after 2.4 s (NATS schedules at whole seconds, and the transport rounds a delay up, so a message is never early). In front of the 2.11.17 hub, the setup is refused before anything is written: the hub has no stream, and the refusal says what decided, API level 1. The delayed sends are refused with the same reason and store nothing.

Through a leaf node 5.12.2 5.13.0
2.11.17 in front of a 2.15.3 hub setup and delayed sends refused set up, both reminders arrive
2.15.3 in front of a 2.11.17 hub stream written, setup fails, 2 messages stored, none delivered refused, nothing written
2.11.17, a user without $JS.hub.API.INFO refused by the leaf node's release refused by the leaf node's release, with the reason

A user who may not ask

The third case is the fallback. nolevel may not publish to $JS.hub.API.INFO, so the server refuses the question. The transport then goes by the connected server's version, as 5.12.2 did, for the rest of that connection, and the refusal now says so, with the client's reason, including the subject to grant. The client logs one error line for the refused request, once per connection: the first line of that case. On a leaf node of 2.12 or later in front of an older hub, such a user is back to what 5.12.2 did: a setup that fails only after it has written the stream.

A read that fails in another way decides only the call it was made for. A JetStream error, a failure on the connection or a timeout leaves that one call to the version, and the next setup or delayed send asks again. Any other exception propagates.

So with scheduled_messages, a worker's user now publishes to $JS.API.INFO, or to $JS.<domain>.API.INFO with jetstream_domain, or to its form under jetstream_api_prefix: once per connection, at the setup and at the first delayed send. The README's "Permissions a Worker Needs" lists it. Without a leaf node, the release notes say, the decision is the same as before; only the refusals' wording after their first words changed.

5.12.1: the warning names the subject to grant

With retry_via: nak, the transport asks the consumer for its own max_deliver at the first retry that needs it, because the retry of the last delivery max_deliver allows has to go out as a copy (our 5.12 post shows why). A user who may not ask gets a warning and the max_deliver option decides. That warning ended with the subject to grant, and up to 5.12.0 it named $JS.API.CONSUMER.INFO.<stream>.<consumer> even under jetstream_domain or jetstream_api_prefix, a subject the transport does not use then.

consumer-warning.php runs on the same leaf node as noread, whose only missing grant is $JS.hub.API.CONSUMER.INFO.orders.worker. The handler fails once, so the first retry asks for the consumer and is refused:

php
<?php

// retry_via: nak on the leaf node, as the user noread, who may not read its consumer.
// The handler fails once, so the first retry asks the consumer for its max_deliver
// and is refused. Run: php consumer-warning.php (needs the servers 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 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\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 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;
    }
}

/** Prints the warnings the transport logs. */
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";
        }
    }
}

$leaf = '127.0.0.1:14792/orders/orders.placed';
$options = 'jetstream_domain=hub&consumer=worker&retry_via=nak&max_deliver=3'
    . '&max_batch_timeout=0.5';

// Start without the stream: delete it on the hub itself.
$hub = (new NatsTransportConfigurationBuilder())
    ->build('nats-jetstream://127.0.0.1:14791/x/x')->client;
$hub->connect()->await();
try {
    $hub->jetStream()->deleteStream('orders')->await();
} catch (Throwable) {
}
$hub->disconnect()->await();

// The application's user sets up the stream and the consumer on the hub, and sends.
$app = new NatsTransport("nats-jetstream://app:app@$leaf?$options", [],
    new PhpSerializer());
$app->setup();
$app->send(new Envelope(new OrderPlaced(7)));
$app->close();

printf(
    "symfony-nats-messenger %s, a worker as noread on the leaf node\n",
    InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
);
$runs = 0;
$bus = new MessageBus([new HandleMessageMiddleware(new HandlersLocator([
    OrderPlaced::class => [function (OrderPlaced $order) use (&$runs): void {
        if (++$runs === 1) {
            throw new RuntimeException("the carrier API is down ({$order->order})");
        }
        echo "  handler run $runs: order {$order->order} shipped\n";
    }],
]))]);
$worker = new NatsTransport(
    "nats-jetstream://noread:noread@$leaf?$options",
    [],
    new PhpSerializer(),
    new Warnings(),
);
$events = new EventDispatcher();
$events->addSubscriber(new SendFailedMessageForRetryListener(
    new One($worker),
    new One(new MultiplierRetryStrategy(1, 100, 1)),
));
$events->addSubscriber(new StopWorkerOnTimeLimitListener(4));
(new Worker(['orders' => $worker], $bus, $events))->run(['sleep' => 100000]);
printf("worker: ended at its time limit, %d handler runs\n", $runs);
$worker->close();

On 5.12.0 (php consumer-warning.php):

text
symfony-nats-messenger v5.12.0, a worker as noread on the leaf node
  warning: retry_via=nak on stream "orders": consumer "worker" could not be read for
    its max_deliver (The server refused the request to
    "$JS.hub.API.CONSUMER.INFO.orders.worker": Permissions Violation for Publish to
    "$JS.hub.API.CONSUMER.INFO.orders.worker". No responder received it. Grant this
    connection's user permission to publish to
    "$JS.hub.API.CONSUMER.INFO.orders.worker".), so the max_deliver option (3) tells
    which delivery is the last one. Let this user ask for consumer info
    ($JS.API.CONSUMER.INFO.orders.worker).
  handler run 2: order 7 shipped
worker: ended at its time limit, 2 handler runs

The client's own message, in the brackets, already had it right. The transport's advice at the end did not: granting $JS.API.CONSUMER.INFO.orders.worker would change nothing on this leaf node. On 5.12.1:

text
symfony-nats-messenger v5.12.1, a worker as noread on the leaf node
  warning: retry_via=nak on stream "orders": consumer "worker" could not be read for
    its max_deliver (The server refused the request to
    "$JS.hub.API.CONSUMER.INFO.orders.worker": Permissions Violation for Publish to
    "$JS.hub.API.CONSUMER.INFO.orders.worker". No responder received it. Grant this
    connection's user permission to publish to
    "$JS.hub.API.CONSUMER.INFO.orders.worker".), so the max_deliver option (3) tells
    which delivery is the last one. Let this user ask for consumer info
    ($JS.hub.API.CONSUMER.INFO.orders.worker).
  handler run 2: order 7 shipped
worker: ended at its time limit, 2 handler runs

The advice now names the subject the server refused. Without either option the warning is unchanged. 5.12.1 also updated the README: "Permissions a Worker Needs" says that jetstream_domain and jetstream_api_prefix move every JetStream API subject in its list, and "JetStream Domains and Leaf Nodes" gives a worker's grants on a leaf node and through an account import.

5.12.2: a leader change no longer ends the worker

In a cluster, while the leader of a worker's consumer changes, the cluster answers a pull with status 503, the status of a missing consumer. The transport then asks the client why, and the client asks the cluster about the consumer. During the change that question goes unanswered: a member of the consumer's group that is not its leader drops it. So after request_timeout (10 s by default) the transport had no answer, the 503 propagated, and messenger:consume stopped, reconnect: true or not. 5.12.2 asks once more after an unanswered question, and a consumer that either question finds makes that get() an empty one.

Three servers of nats-server 2.15.3, with restart: always, so a stopped server comes back:

yaml
# Three servers of the cluster "east", nats-server 2.15.3, JetStream on each.
# restart: always brings a stopped server back. Host ports: c1 14801, c2 14802, c3 14803.
x-server: &server
  image: nats:2.15.3-alpine
  restart: always
services:
  c1:
    <<: *server
    command: ["-js", "-n", "c1", "--cluster_name", "east",
      "--cluster", "nats://0.0.0.0:6222", "--routes", "nats://c2:6222,nats://c3:6222",
      "--client_advertise", "127.0.0.1:14801"]
    ports: ["14801:4222"]
  c2:
    <<: *server
    command: ["-js", "-n", "c2", "--cluster_name", "east",
      "--cluster", "nats://0.0.0.0:6222", "--routes", "nats://c1:6222,nats://c3:6222",
      "--client_advertise", "127.0.0.1:14802"]
    ports: ["14802:4222"]
  c3:
    <<: *server
    command: ["-js", "-n", "c3", "--cluster_name", "east",
      "--cluster", "nats://0.0.0.0:6222", "--routes", "nats://c1:6222,nats://c2:6222",
      "--client_advertise", "127.0.0.1:14803"]
    ports: ["14803:4222"]

leader.php uses the same composer.json. It creates a stream with three replicas, finds the server that leads the consumer, and runs a worker with reconnect: true on another server. After 2 seconds it stops the leader with SIGTERM, which is what docker stop sends, and a second connection watches the consumer's leader every half second:

php
<?php

// A worker with reconnect: true on one server of the cluster, its consumer led by
// another, which is stopped with SIGTERM (what docker stop sends) and comes back
// (restart: always). A second connection watches the consumer's leader.
// Run: php leader.php [request_timeout, default 10] (needs the servers of compose.yaml)

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Composer\InstalledVersions;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;

use function Amp\async;
use function Amp\delay;

final class Job
{
    public function __construct(public readonly int $id)
    {
    }
}

const PORTS = ['c1' => 14801, 'c2' => 14802, 'c3' => 14803];
define('QUERY', 'consumer=worker&stream_replicas=3&max_batch_timeout=1&reconnect=true'
    . '&request_timeout=' . ($argv[1] ?? '10'));

function dsn(string $server, string $query = QUERY): string
{
    return 'nats-jetstream://127.0.0.1:' . PORTS[$server] . "/jobs/jobs.run?$query";
}

// A fresh stream with three replicas, and the server that leads its consumer. A server
// the last run stopped may still be on its way back: try for up to 60 s.
for ($try = 1; ; $try++) {
    try {
        $admin = (new NatsTransportConfigurationBuilder())->build(dsn('c1'))->client;
        $admin->connect()->await();
        try {
            $admin->jetStream()->deleteStream('jobs')->await();
        } catch (JetStreamException) {
        }
        (new NatsTransport(dsn('c1'), [], new PhpSerializer()))->setup();
        break;
    } catch (Throwable $e) {
        $try < 30 ? sleep(2) : throw $e;
    }
}
for ($leader = null; $leader === null; usleep(200_000)) {
    try {
        $info = $admin->jetStream()->getConsumer('jobs', 'worker')->await()->raw;
        $leader = $info['cluster']['leader'] ?? null;
    } catch (JetStreamException) {
    }
}
$admin->disconnect()->await();
$on = array_values(array_diff(array_keys(PORTS), [$leader]))[0];

printf(
    "symfony-nats-messenger %s, request_timeout %s s\n"
    . "the consumer led by %s, the worker on %s\n",
    InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
    $argv[1] ?? '10',
    $leader,
    $on,
);
$worker = new NatsTransport(dsn($on), [], new PhpSerializer());
$sender = new NatsTransport(dsn($on), [], new PhpSerializer());
$sender->send(new Envelope(new Job(1)));

$start = microtime(true);
$quiet = 0;
$say = function (string $line) use (&$quiet, $start): void {
    if ($quiet > 0) {
        printf("        %d empty get() calls of about 1 s\n", $quiet);
        $quiet = 0;
    }
    $line = wordwrap($line, 78, "\n         ", true);
    printf("%5.1f s  %s\n", microtime(true) - $start, $line);
};

// The watcher asks the worker's server for the consumer every 0.5 s, with a 1 s timeout.
$watch = (new NatsTransportConfigurationBuilder())
    ->build(dsn($on, 'request_timeout=1'))->client;
$watch->connect()->await();
$watching = true;
$watcher = async(function () use ($watch, &$watching, $say): void {
    $last = null;
    while ($watching) {
        try {
            $raw = $watch->jetStream()->getConsumer('jobs', 'worker')->await()->raw;
            $now = $raw['cluster']['leader'] ?? 'none';
        } catch (JetStreamException $e) {
            $now = 'none (' . $e->getMessage() . ')';
        } catch (Throwable) {
            $now = 'none (no answer)';
        }
        if ($now !== $last) {
            $say("watcher: the consumer's leader is $now");
            $last = $now;
        }
        delay(0.5);
    }
});

$stopped = $sent = false;
while (microtime(true) - $start < 32) {
    if (!$stopped && microtime(true) - $start > 2) {
        $stop = "docker exec leader-change-$leader-1 nats-server --signal term=1";
        exec($stop, $out, $code);
        $say("$leader, the consumer's leader, stopped with SIGTERM (exit $code)");
        $stopped = true;
    }
    if (!$sent && microtime(true) - $start > 24) {
        $sender->send(new Envelope(new Job(2)));
        $say('job 2 sent');
        $sent = true;
    }
    $began = microtime(true);
    try {
        $jobs = [];
        foreach ($worker->get() as $envelope) {
            $jobs[] = 'job ' . $envelope->getMessage()->id;
            $worker->ack($envelope);
        }
    } catch (Throwable $e) {
        $name = (new ReflectionClass($e))->getShortName();
        $say(sprintf('get() threw after %.1f s: %s: %s', microtime(true) - $began, $name,
            $e->getMessage()));
        $say('messenger:consume stops here');
        break;
    }
    $took = microtime(true) - $began;
    if ($jobs === [] && $took < 1.5) {
        $quiet++;
        continue;
    }
    $got = $jobs === [] ? 'empty' : implode(', ', $jobs);
    $say(sprintf('get() took %.1f s: %s', $took, $got));
}
$watching = false;
$watcher->await();
$say('the run ends');
$worker->close();
$sender->close();
$watch->disconnect()->await();

On 5.12.1 (docker compose up --detach, then php leader.php):

text
symfony-nats-messenger v5.12.1, request_timeout 10 s
the consumer led by c2, the worker on c1
  0.0 s  watcher: the consumer's leader is c2
  0.0 s  get() took 0.0 s: job 1
        2 empty get() calls of about 1 s
  2.1 s  c2, the consumer's leader, stopped with SIGTERM (exit 0)
  3.1 s  watcher: the consumer's leader is none (no answer)
  3.8 s  watcher: the consumer's leader is none (JetStream system temporarily
         unavailable)
 12.1 s  get() threw after 10.0 s: JetStreamException: JetStream pull request ended
         with status 503
 12.1 s  messenger:consume stops here
 12.3 s  the run ends

The pull got its 503 right after the stop, the question about the consumer went unanswered for 10 seconds, and the worker stopped, though the server it was connected to never went away. On 5.12.2:

text
symfony-nats-messenger v5.12.2, request_timeout 10 s
the consumer led by c1, the worker on c2
  0.0 s  watcher: the consumer's leader is c1
  0.0 s  get() took 0.0 s: job 1
        2 empty get() calls of about 1 s
  2.1 s  c1, the consumer's leader, stopped with SIGTERM (exit 0)
  3.1 s  watcher: the consumer's leader is none (no answer)
  3.6 s  watcher: the consumer's leader is none (JetStream system temporarily
         unavailable)
 10.1 s  watcher: the consumer's leader is none (no answer)
 10.6 s  watcher: the consumer's leader is c2
 12.1 s  get() took 10.0 s: empty
        4 empty get() calls of about 1 s
 19.5 s  get() took 3.1 s: empty
        5 empty get() calls of about 1 s
 24.5 s  job 2 sent
 24.5 s  get() took 0.0 s: job 2
        5 empty get() calls of about 1 s
 34.2 s  watcher: the consumer's leader is none (no answer)
 34.2 s  get() took 4.7 s: empty
 34.7 s  the run ends

Here the watcher saw a new leader 8.5 seconds after the stop. The first question went unanswered, the second found the consumer, and the pull came back empty after 10 seconds instead of throwing. The worker went on and got job 2. Two later pulls took longer (3.1 and 4.7 s) and returned empty, with the watcher's question going unanswered once near the end; c1 had come back by then, about 8 seconds after its stop according to its log, and the worker carried on through both.

The fix has an edge, and our runs found it. The second question goes out one request_timeout after the first. If the consumer still has no leader then, the cluster answers "JetStream system temporarily unavailable", a JetStream error, and the 503 keeps its reading. In the 5.12.1 run above, the server logs show the new leader 14.4 seconds after the stop, so 5.12.2 would have stopped there too. In two earlier 5.12.2 runs on this busy box, with logging added to a copy of the transport, that is what happened: the second question got that error, and the worker stopped as on 5.12.1. Elections we saw took from about 1.5 to 15 seconds. A longer request_timeout gives a slow election more room, at the price of a longer wait in that get() and in every other request that gets no answer.

One more change comes with it: a user who may pull but not ask for consumer info now gets a missing consumer's 503 after twice request_timeout, where it got it after one. The README's "Automatic Reconnect", "Losing a Server" and "Provisioning the Stream & Consumer" now say what a change of the consumer's leader costs a worker.

Upgrading

bash
composer update idct/symfony-nats-messenger

The client floor stays at php-nats-jetstream-client 2.39.1. Then, from the README's upgrade sections:

  • With scheduled_messages on a leaf node, an old leaf node in front of a new hub now sets up and sends delayed messages; a new leaf node in front of an old hub is now refused before the setup writes anything. Without a leaf node nothing changes.
  • Grant $JS.API.INFO (or its form under your domain or prefix) to a user with scheduled_messages. Without it the transport falls back to the version check, and the client logs one error line per connection.
  • Log alerts: the refusals keep their first words, so an alert on The 'scheduled_messages' option requires NATS Server >= 2.12 or The delayed message was not sent still matches. One that matches the old $JS.API.CONSUMER.INFO subject of the unreadable-consumer warning under a domain or prefix needs the new one.
  • In a cluster, nothing to configure for 5.12.2. A supervisor that restarted workers after a leader change restarts fewer.

How it is tested

The README now counts 1753 unit tests at about 99.8% coverage, and docs/TESTS.md keeps the mutation score of 98.6% recorded on 29 November. For 5.13.0, unit tests stub the account info with a level, and check that the level is read once per connection, that a refused read falls back to the version for the rest of the connection, and that the question goes out under the domain or the prefix. The project's test setup gained a second leaf node, pinned to NATS 2.11, in front of its test hub, and the Behat scenario "A transport with scheduled messages on a leaf node older than 2.12 sets up and its delayed messages arrive through the hub" runs on it. For 5.12.2, GracefulStopPullTest covers each order of answers, with doubles and with the real client over a scripted server that leaves the first question unanswered. For 5.12.1, one unit test checks the warning's subject under the domain and the prefix.

Get it