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

php-nats-jetstream-client 2.37: the server's answer decides

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

2.37.0 stops refusing JetStream calls because of the version the connected server reports: in a cluster halfway through a rolling upgrade, or behind a leaf node, the server that answers decides. We ran both, plus seven patch releases.

idct/php-nats-jetstream-client 2.37.0 is out, and it takes something away. From 2.31.0 to 2.36.7 the client looked at the version the connected NATS server reports in its INFO and refused calls that server was too old for: a counter stream, a recurring schedule, an atomic batch, a consumer reset. The trouble is that the connected server is often not the one that answers. 2.37.0 sends every JetStream request and lets the server that handles it decide.

Our last post on the client covered 2.36.0, so this one also covers the seven patch releases since, three of them security fixes. We ran every example below on PHP 8.5.9 with 2.36.0, 2.36.7 and 2.37.0 from Packagist, against nats-server 2.10.29, 2.11.17, 2.12.15 and 2.14.10 in Docker: a three-node cluster halfway through a rolling upgrade, a 2.12 leaf node in front of a 2.14 hub, and one standalone server per release. The output is pasted as it came out.

Why the connected server is the wrong one to ask

A JetStream request does not stop at the server your client is connected to. It is answered by the cluster's meta leader or by the server that hosts the stream or consumer. In a cluster under a rolling upgrade those can run a newer release than your node. Behind a leaf node, the hub that holds the streams can run a newer release than the leaf. In both cases the client compared the wrong version, refused a valid call with nothing was sent, and gave you no way around it.

ADR-44 revision 4 now makes this a rule for every NATS client: a client must not refuse a feature, choose an API subject, change or drop a config field or fall back to an older API because of that version. The team's own daily review filed issue #272 the day the revision was merged, and 2.37.0 removes all five decisions the client made from it:

GitHub release page of php-nats-jetstream-client v2.37.0: every JetStream request goes out whatever version the connected server reports, and five version decisions are gone

Some of those refusals were the subject of our own posts: 2.31 refused schedules a 2.12 server cannot run, 2.32 refused stream fields a 2.10 or 2.11 server would drop, and 2.34 showed resetConsumer() refused through a 2.12 leaf node although the 2.14 hub behind it would have answered. What stays is the part that judges the server's answer: a stream created without a field the server dropped still ends in an UnsupportedFeatureException, so you are still told when a feature did not take.

Upgrading

bash
composer require idct/php-nats-jetstream-client:^2.37

On a cluster where every server runs the same release, nothing changes. What does change:

  • Mixed releases now work. A cluster in the middle of an upgrade, a leaf node, or an account import in front of a newer server: the calls the server accepts go through.
  • Older servers answer for themselves. Where 2.36.7 refused at once with code 0, you now get the server's own error, an exception after the server created something without the field, or a timeout. The list is in the section on older servers below. Read it before you upgrade if you run 2.10, 2.11 or 2.12 anywhere.
  • AccountInfo::$apiLevel is new. It is the JetStream API level accountInfo() reports, answered by the meta leader. Check it, not the server version, when your code needs to know what the cluster supports.
  • Two methods are deprecated: FeatureSupport::serverIsOlderThan() and JetStreamContext::supportsBatchedDirectGet(). The library no longer calls either, and both go in the next major release. Three @internal methods are removed.
  • Three patch releases since 2.36.0 fix security issues (2.36.3, 2.36.4, 2.36.6). If you stayed on 2.36.0, that alone is a reason to move.

The full record is in the changelog at v2.37.0.

A proof of concept you can run

Two Docker Compose projects. The first is the cluster: n1 and n2 already run 2.12 and carry the server tag upgraded, n3 still runs 2.11. All three load the same accounts: the application's, and a system account, which you need if you ever want to move the meta leader with a step-down request:

yaml
services:
  # A cluster halfway through a rolling upgrade: n1 and n2 run 2.12, n3 still 2.11.
  n1:
    image: nats:2.12-alpine
    command: ["-c", "/etc/nats/n1.conf"]
    volumes:
      - ./n1.conf:/etc/nats/n1.conf:ro
      - ./accounts.conf:/etc/nats/accounts.conf:ro
    ports: ["14731:4222"]
  n2:
    image: nats:2.12-alpine
    command: ["-c", "/etc/nats/n2.conf"]
    volumes:
      - ./n2.conf:/etc/nats/n2.conf:ro
      - ./accounts.conf:/etc/nats/accounts.conf:ro
    ports: ["14732:4222"]
  n3:
    image: nats:2.11-alpine
    command: ["-c", "/etc/nats/n3.conf"]
    volumes:
      - ./n3.conf:/etc/nats/n3.conf:ro
      - ./accounts.conf:/etc/nats/accounts.conf:ro
    ports: ["14733:4222", "14743:8222"]
text
# n1.conf: upgraded to nats-server 2.12 already.
server_name: n1
port: 4222
http_port: 8222
server_tags: ["upgraded"]

jetstream {}

cluster {
  name: rolling
  port: 6222
  routes: ["nats://n1:6222", "nats://n2:6222", "nats://n3:6222"]
}

include ./accounts.conf
text
# n3.conf: still on nats-server 2.11, next in line for the upgrade.
server_name: n3
port: 4222
http_port: 8222
server_tags: ["not-upgraded"]

jetstream {}

cluster {
  name: rolling
  port: 6222
  routes: ["nats://n1:6222", "nats://n2:6222", "nats://n3:6222"]
}

include ./accounts.conf
text
# accounts.conf: the application's account, and the system account for operator requests.
accounts {
  APP: {
    jetstream: enabled
    users: [{ user: app, password: demo }]
  }
  SYS: {
    users: [{ user: sys, password: demo }]
  }
}
system_account: SYS

n2.conf is n1.conf with its own name. One thing we learned while setting it up: our first version made n3 wait until n1 and n2 passed a health check. They never did. With three servers in their routes, n1 and n2 alone elected no meta leader in over a minute, so start all three together.

The second project holds the leaf node and its hub, one standalone server per release, and a server with users for two of the patch releases:

yaml
services:
  # A 2.12 leaf node in front of a 2.14 hub that runs JetStream in the domain "hub".
  hub:
    image: nats:2.14-alpine
    command: ["-c", "/etc/nats/hub.conf"]
    volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
    ports: ["14704:4222"]
  leaf:
    image: nats:2.12-alpine
    command: ["-c", "/etc/nats/leaf.conf"]
    volumes: ["./leaf.conf:/etc/nats/leaf.conf:ro"]
    ports: ["14705:4222"]
    depends_on: [hub]
  # One standalone server per release, for what a call on an older server returns.
  nats-2-10:
    image: nats:2.10-alpine
    command: ["-js", "-n", "nats-2-10"]
    ports: ["14710:4222"]
  nats-2-11:
    image: nats:2.11-alpine
    command: ["-js", "-n", "nats-2-11"]
    ports: ["14711:4222"]
  nats-2-12:
    image: nats:2.12-alpine
    command: ["-js", "-n", "nats-2-12"]
    ports: ["14712:4222"]
  nats-2-14:
    image: nats:2.14-alpine
    command: ["-js", "-n", "nats-2-14"]
    ports: ["14714:4222"]
  # Users with limited permissions, for two of the patch releases.
  perm:
    image: nats:2.14-alpine
    command: ["-c", "/etc/nats/perm.conf"]
    volumes: ["./perm.conf:/etc/nats/perm.conf:ro"]
    ports: ["14720:4222"]
text
# hub.conf: nats-server 2.14, JetStream in the domain "hub", and a port for leaf nodes.
server_name: hub
port: 4222

jetstream {
  domain: hub
}

leafnodes {
  port: 7422
}
text
# leaf.conf: nats-server 2.12 without JetStream of its own, connected to the hub.
server_name: leaf
port: 4222

leafnodes {
  remotes: [
    { url: "nats-leaf://hub:7422" }
  ]
}
text
# perm.conf: an admin, and a worker that may pull from JOBS/work but not JOBS/audit.
port: 4222

jetstream {}

authorization {
  users = [
    { user: admin, password: demo }
    {
      user: worker, password: demo
      permissions: {
        publish: {
          allow: ["$JS.API.>", "svc.ok"]
          deny: ["$JS.API.CONSUMER.MSG.NEXT.JOBS.audit"]
        }
        subscribe: ["_INBOX.>"]
      }
    }
  ]
}
json
{
    "require": {
        "php": "^8.2",
        "idct/php-nats-jetstream-client": "^2.37"
    }
}

Every script loads a few helpers. connect() prints the client version and what the connected server's INFO says, and apiLevel() reads the new property, or the raw reply on a version that does not have it yet:

php
<?php
// lib.php: the helpers every script here shares.
declare(strict_types=1);

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

use Composer\InstalledVersions;
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\JetStreamContext;
use IDCT\NATS\JetStream\Models\StreamInfo;

/** Connects, and says which client and which server (as its INFO reports it) we use. */
function connect(string $url, mixed ...$options): NatsClient
{
    $client = new NatsClient(new NatsOptions(...['servers' => [$url], ...$options]));
    $client->connect()->await();
    $info = $client->serverInfo();
    $name = (string) $info?->serverName;
    printf("client %s, connected to %s, nats-server %s (INFO)\n",
        InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client'),
        strlen($name) > 16 ? substr($name, 0, 8) . '...' : $name, $info?->version);

    return $client;
}

/** The JetStream API level the account info reports (AccountInfo::$apiLevel, 2.37+). */
function apiLevel(JetStreamContext $js): string
{
    $account = $js->accountInfo()->await();
    if (!property_exists($account, 'apiLevel')) {
        return 'API level ' . ($account->raw['api']['level'] ?? 'none')
            . ' (raw reply: no AccountInfo::$apiLevel before 2.37)';
    }

    return 'AccountInfo::$apiLevel ' . ($account->apiLevel ?? 'null');
}

/** Deletes the stream if it is there, then creates it. */
function fresh(
    JetStreamContext $js, string $name, array $subjects, array $options = [],
): StreamInfo
{
    try {
        $js->deleteStream($name)->await();
    } catch (JetStreamException) {
        // first run: nothing to delete
    }

    return $js->createStream($name, $subjects, $options)->await();
}

/** "UnsupportedFeatureException (code 0): ..." for any failure, with its err_code. */
function failure(\Throwable $e): string
{
    $errCode = method_exists($e, 'getErrCode') ? $e->getErrCode() : null;

    return sprintf('%s (code %d%s): %s', (new \ReflectionClass($e))->getShortName(),
        $e->getCode(), $errCode === null ? '' : ", err_code $errCode", $e->getMessage());
}

/** Prints $text wrapped at 82 columns, the next lines indented. */
function line(string $text, string $indent = '      '): void
{
    echo wordwrap($text, 82, "\n" . $indent, true), PHP_EOL;
}

/** Seconds since $start (an hrtime(true) value), as "0.004 s". */
function since(int|float $start): string
{
    return sprintf('%.3f s', (hrtime(true) - $start) / 1e9);
}

The commands, in the order of this post. We ran each script in a 2.37.0 install and in the version it is compared with:

bash
(cd rolling-upgrade && docker compose up -d)
(cd mixed-versions && docker compose up -d)
composer install
php upgrade.php
php leaf.php
for p in 14710 14711 14712 14714; do php older.php nats://127.0.0.1:$p; done
php patches.php

A cluster halfway through a rolling upgrade

This is the case from issue #272, rebuilt. The application connects to n3, the node that is next in line for the upgrade. It asks for a counter stream (allow_msg_counter, a 2.12 feature) twice: once placed on the upgraded nodes, once on n3 itself.

php
<?php
// upgrade.php: a cluster halfway through a rolling upgrade, seen from the old node.
declare(strict_types=1);

require __DIR__ . '/lib.php';

// n3, with a 3 s request timeout instead of the default 10 s.
$client = connect('nats://127.0.0.1:14733', username: 'app', password: 'demo',
    requestTimeoutMs: 3000);
$js = $client->jetStream();

// Who answers JetStream: the meta leader (from n3's monitoring port) and its API level.
$jsz = json_decode(file_get_contents('http://127.0.0.1:14743/jsz'), true);
printf("  meta leader %s; %s\n", $jsz['meta_cluster']['leader'], apiLevel($js));

// The same counter stream twice: once on the upgraded nodes, once on n3 itself.
$cases = [
    ['HITS', 'hits', 'upgraded'],
    ['HITS_N3', 'hits-n3', 'not-upgraded'],
];
foreach ($cases as [$stream, $prefix, $tag]) {
    echo "\ncreateStream($stream, allow_msg_counter, placement tag \"$tag\")\n";
    try {
        $info = fresh($js, $stream, ["$prefix.>"], [
            'allow_msg_counter' => true,
            'allow_direct' => true,
            'placement' => ['tags' => [$tag]],
        ]);
    } catch (\Throwable $e) {
        line('  ' . failure($e));
        try {
            $config = $js->getStream($stream)->await()->raw['config'];
            printf("  the stream exists, allow_msg_counter: %s\n",
                json_encode($config['allow_msg_counter'] ?? '(not in its config)'));
        } catch (\Throwable $e) {
            line('  getStream(): ' . failure($e));
        }
        continue;
    }
    printf("  created, stream leader %s\n", $info->raw['cluster']['leader'] ?? '?');
    $js->incrementCounter("$prefix.home", '+1')->await();
    printf("  incrementCounter +1, +2: total %s\n",
        $js->incrementCounter("$prefix.home", '+2')->await());
}
$client->disconnect()->await();

With 2.36.7:

text
client v2.36.7, connected to n3, nats-server 2.11.17 (INFO)
  meta leader n1; API level 3 (raw reply: no AccountInfo::$apiLevel before 2.37)

createStream(HITS, allow_msg_counter, placement tag "upgraded")
  UnsupportedFeatureException (code 0): The "allow_msg_counter" feature requires
      NATS server 2.12+, but the connected server reports 2.11.17 (nothing was sent: an
      older server ignores the field and would set up the stream without it)
  getStream(): JetStreamException (code 404, err_code 10059): stream not found

createStream(HITS_N3, allow_msg_counter, placement tag "not-upgraded")
  UnsupportedFeatureException (code 0): The "allow_msg_counter" feature requires
      NATS server 2.12+, but the connected server reports 2.11.17 (nothing was sent: an
      older server ignores the field and would set up the stream without it)
  getStream(): JetStreamException (code 404, err_code 10059): stream not found

With 2.37.0:

text
client v2.37.0, connected to n3, nats-server 2.11.17 (INFO)
  meta leader n1; AccountInfo::$apiLevel 3

createStream(HITS, allow_msg_counter, placement tag "upgraded")
  created, stream leader n1
  incrementCounter +1, +2: total 3

createStream(HITS_N3, allow_msg_counter, placement tag "not-upgraded")
  TimeoutException (code 0): Request timed out for subject
      $JS.API.STREAM.CREATE.HITS_N3
  getStream(): UnsupportedFeatureException (code 500, err_code 10194): The
      "allow_msg_counter" feature requires NATS server 2.12+, but the connected server
      reports 2.11.17. (stream is offline: unsupported - config error: unknown field
      "allow_msg_counter")
  • The version in INFO was not the version that mattered. n3 says 2.11.17, but the meta leader is n1, which reports API level 3: a 2.12 server. 2.36.7 refused both streams on n3's word, and nothing reached the cluster.
  • On the upgraded nodes, 2.37.0 just works. The stream was created on n1, and the counter added up to 3 through n3.
  • On the old node, the create times out. This is not in the release notes; we found it here. The meta leader accepted the stream and placed it on n3, but nats-server 2.11 does not run a stream it cannot fully read. It sets it aside as unsupported, so no server answered the create, and the client gave up after our 3 s request timeout. The stream exists, offline, as getStream() shows, and n3's log says why. In rolling-upgrade/, the last two such lines are from this run:
bash
docker compose logs --no-log-prefix n3 | grep unsupported | tail -2 \
  | fold -s -w 88 | sed 's/ *$//'
text
[1] 2026/11/30 07:41:41.153067 [WRN] Detected unsupported stream 'APP > HITS':
unsupported - config error: unknown field "allow_msg_counter"
[1] 2026/11/30 07:41:41.155569 [WRN] Detected unsupported stream 'APP > HITS_N3':
unsupported - config error: unknown field "allow_msg_counter"

That is a safer failure than a default 2.10 server gives, which drops the field and creates the stream anyway (more on that below), but it is a timeout, not an error, and it leaves an offline stream behind. Two takeaways for a rolling upgrade: place streams that need the new release on upgraded nodes, by tag as here, or wait until the last node is done; and if your code has to choose, choose from accountInfo()->apiLevel, which comes from the meta leader. The message of the getStream() exception names "the connected server", which here happens to be the node that holds the stream; the changelog says the version in that exception is for information only.

The issue explains why the old behaviour could not stay:

Issue 272 of php-nats-jetstream-client, Why it matters: during a rolling upgrade some application instances are refused stream creates, schedules and batch commits that the cluster accepts

Through a 2.12 leaf node to a 2.14 hub

A PHP service on an edge site connects to its local leaf node, which runs 2.12, and uses the hub's JetStream through the hub domain. The hub runs 2.14. leaf.php asks for two 2.14 features through the leaf: a consumer reset and a recurring schedule.

php
<?php
// leaf.php: a 2.12 leaf node in front of a 2.14 hub, which holds the stream.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\Schedule;

use function Amp\delay;

$client = connect('nats://127.0.0.1:14705', requestTimeoutMs: 3000); // the leaf
$js = $client->jetStream(domain: 'hub');
line('  through the leaf to the hub: ' . apiLevel($js));

fresh($js, 'TASKS', ['tasks.>', 'ticks.>'], ['allow_msg_schedules' => true]);
$js->createConsumer('TASKS', 'worker', 'tasks.>', ['ack_policy' => 'explicit'])->await();
foreach (['resize', 'thumbnail', 'publish'] as $task) {
    $js->publish("tasks.$task", $task)->await();
}
$payloads = function () use ($js): string {
    $taken = [];
    foreach ($js->fetchBatch('TASKS', 'worker', 3, 1000)->await() as $message) {
        $js->ack($message)->await();
        $taken[] = $message->payload;
    }

    return implode(', ', $taken);
};
echo '  the worker takes and acks: ', $payloads(), PHP_EOL;

// 1. Rewind the worker to the first task: a 2.14 API.
try {
    $reset = $js->resetConsumer('TASKS', 'worker', 1)->await();
    printf("  resetConsumer(seq 1): next delivery from s%d\n", $reset->resetSequence);
    echo '  the worker takes them again: ', $payloads(), PHP_EOL;
} catch (\Throwable $e) {
    line('  resetConsumer(): ' . failure($e));
}

// 2. A recurring schedule: 2.14 again.
try {
    $ack = $js->publishScheduled('ticks.schedule', 'ticks.fired', 'tick',
        Schedule::every('1s'))->await();
    printf("  publishScheduled(@every 1s): stored at s%d\n", $ack->seq);
    delay(3.5);
    $fired = 0;
    $from = 0;
    try {
        while (true) {
            $from = $js->getNextMessageForSubject('TASKS', 'ticks.fired', $from)
                ->await()->sequence + 1;
            $fired++;
        }
    } catch (JetStreamException $e) {
        if ($e->getErrCode() !== 10037) { // 10037: no message found, the end
            throw $e;
        }
    }
    printf("  3.5 s later, ticks.fired holds %d message(s)\n", $fired);
} catch (\Throwable $e) {
    line('  publishScheduled(): ' . failure($e));
}

$js->deleteStream('TASKS')->await(); // stops the schedule
$client->disconnect()->await();

With 2.36.7:

text
client v2.36.7, connected to leaf, nats-server 2.12.15 (INFO)
  through the leaf to the hub: API level 4 (raw reply: no AccountInfo::$apiLevel
      before 2.37)
  the worker takes and acks: resize, thumbnail, publish
  resetConsumer(): UnsupportedFeatureException (code 0): Consumer reset requires
      NATS server 2.14+; older servers do not answer it (connected server 2.12.15;
      nothing was sent)
  publishScheduled(): UnsupportedFeatureException (code 0): The schedule "@every
      1s" requires NATS server 2.14+; older servers accept only "@at" schedules
      (connected server 2.12.15; nothing was published)

With 2.37.0:

text
client v2.37.0, connected to leaf, nats-server 2.12.15 (INFO)
  through the leaf to the hub: AccountInfo::$apiLevel 4
  the worker takes and acks: resize, thumbnail, publish
  resetConsumer(seq 1): next delivery from s1
  the worker takes them again: resize, thumbnail, publish
  publishScheduled(@every 1s): stored at s4
  3.5 s later, ticks.fired holds 3 message(s)
  • The API level tells the truth through the leaf. INFO says 2.12.15; the hub reports API level 4, which is 2.14.
  • The reset our 2.34 post could not do now works. The worker had acked all three tasks; after the reset to sequence 1 it took all three again.
  • So does the recurring schedule. The hub stored it, and in 3.5 s it fired three times. The script deletes the stream at the end, which also stops the schedule.

What an older server answers now

The other side of the change: when the server that answers really is too old, it is now the server that says so, and the answers differ. older.php makes four calls on each standalone server, with a 1.5 s request timeout:

php
<?php
// older.php: what a call on an older server returns, now that every request goes out.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\JetStream\JetStreamContext;
use IDCT\NATS\JetStream\Schedule;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14710', requestTimeoutMs: 1500);
$js = $client->jetStream();
echo '  ', apiLevel($js), PHP_EOL;

/** Runs $call and prints what it returned or threw, and how long it took. */
function attempt(string $label, callable $call): bool
{
    $start = hrtime(true);
    try {
        line(sprintf('  %s: %s', $label, $call()));
        return true;
    } catch (\Throwable $e) {
        line(sprintf('  %s: %s, after %s', $label, failure($e), since($start)));
        return false;
    }
}

/** What the server holds: the stream, a field of its config, its message count. */
function onTheServer(JetStreamContext $js, string $stream, ?string $field = null): void
{
    try {
        $info = $js->getStream($stream)->await()->raw;
    } catch (\Throwable) {
        echo "    on the server: no stream $stream\n";
        return;
    }
    $value = $field === null ? '' : sprintf(', %s: %s', $field,
        json_encode($info['config'][$field] ?? '(not in its config)'));
    printf("    on the server: %s exists%s, %d message(s)\n", $stream, $value,
        $info['state']['messages']);
}

// 1. A stream with a config field that needs 2.12.
attempt('counter stream', function () use ($js): string {
    fresh($js, 'HITS', ['hits.>'], ['allow_msg_counter' => true]);
    return 'created';
});
onTheServer($js, 'HITS', 'allow_msg_counter');

// 2. A recurring schedule, which needs 2.14 (one-off @at schedules: 2.12).
$created = attempt('schedule stream', function () use ($js): string {
    fresh($js, 'SCHED', ['sched.>'], ['allow_msg_schedules' => true]);
    return 'created';
});
if ($created) {
    attempt('@every 1m', fn (): string => 'stored at s' . $js->publishScheduled(
        'sched.report', 'sched.fired', 'build the report', Schedule::every('1m'),
    )->await()->seq);
}

// 3. An atomic batch of three messages (2.12), into a stream without allow_atomic.
fresh($js, 'BATCH', ['batch.>']);
attempt('atomic batch', fn (): string => 'committed, s' . $js->batch()
    ->add('batch.a', '1')->add('batch.b', '2')->add('batch.c', '3')
    ->commit()->await()->seq);
onTheServer($js, 'BATCH');

// 4. A consumer reset, which needs 2.14.
fresh($js, 'RESET', ['reset.>']);
$js->createConsumer('RESET', 'worker', null, ['ack_policy' => 'explicit'])->await();
attempt('resetConsumer', fn (): string => 'next delivery from s'
    . $js->resetConsumer('RESET', 'worker', 1)->await()->resetSequence);

try {
    $js->deleteStream('SCHED')->await(); // stops the 1m schedule
} catch (\Throwable) {
    // no SCHED stream here
}
$client->disconnect()->await();
echo PHP_EOL;

With 2.37.0, on 2.10, 2.11, 2.12 and 2.14:

text
client v2.37.0, connected to nats-2-10, nats-server 2.10.29 (INFO)
  AccountInfo::$apiLevel null
  counter stream: UnsupportedFeatureException (code 0): The "allow_msg_counter"
      feature requires NATS server 2.12+, and the server (connected server reports
      2.10.29) ignored the field: stream "HITS" exists without it (it may have existed
      before this request: inspect it before changing or deleting it), after 0.002 s
    on the server: HITS exists, allow_msg_counter: "(not in its config)", 0 message(s)
  schedule stream: UnsupportedFeatureException (code 0): The "allow_msg_schedules"
      feature requires NATS server 2.12+, and the server (connected server reports
      2.10.29) ignored the field: stream "SCHED" exists without it (it may have existed
      before this request: inspect it before changing or deleting it), after 0.001 s
  atomic batch: UnsupportedFeatureException (code 0): Atomic batch publish
      requires NATS server 2.12+, and the server treated the batch as plain publishes
      (connected server reports 2.10.29), after 0.001 s
    on the server: BATCH exists, 1 message(s)
  resetConsumer: TimeoutException (code 0): Request timed out for subject
      $JS.API.CONSUMER.RESET.RESET.worker, after 1.502 s

client v2.37.0, connected to nats-2-11, nats-server 2.11.17 (INFO)
  AccountInfo::$apiLevel 1
  counter stream: UnsupportedFeatureException (code 0): The "allow_msg_counter"
      feature requires NATS server 2.12+, and the server (connected server reports
      2.11.17) ignored the field: stream "HITS" exists without it (it may have existed
      before this request: inspect it before changing or deleting it), after 0.001 s
    on the server: HITS exists, allow_msg_counter: "(not in its config)", 0 message(s)
  schedule stream: UnsupportedFeatureException (code 0): The "allow_msg_schedules"
      feature requires NATS server 2.12+, and the server (connected server reports
      2.11.17) ignored the field: stream "SCHED" exists without it (it may have existed
      before this request: inspect it before changing or deleting it), after 0.001 s
  atomic batch: UnsupportedFeatureException (code 0): Atomic batch publish
      requires NATS server 2.12+, and the server treated the batch as plain publishes
      (connected server reports 2.11.17), after 0.001 s
    on the server: BATCH exists, 1 message(s)
  resetConsumer: TimeoutException (code 0): Request timed out for subject
      $JS.API.CONSUMER.RESET.RESET.worker, after 1.501 s

client v2.37.0, connected to nats-2-12, nats-server 2.12.15 (INFO)
  AccountInfo::$apiLevel 3
  counter stream: created
    on the server: HITS exists, allow_msg_counter: true, 0 message(s)
  schedule stream: created
  @every 1m: JetStreamException (code 400, err_code 10189): message schedules
      pattern is invalid, after 0.001 s
  atomic batch: JetStreamException (code 400, err_code 10174): atomic publish is
      disabled, after 0.001 s
    on the server: BATCH exists, 0 message(s)
  resetConsumer: TimeoutException (code 0): Request timed out for subject
      $JS.API.CONSUMER.RESET.RESET.worker, after 1.502 s

client v2.37.0, connected to nats-2-14, nats-server 2.14.10 (INFO)
  AccountInfo::$apiLevel 4
  counter stream: created
    on the server: HITS exists, allow_msg_counter: true, 0 message(s)
  schedule stream: created
  @every 1m: stored at s1
  atomic batch: JetStreamException (code 400, err_code 10174): atomic publish is
      disabled, after 0.000 s
    on the server: BATCH exists, 0 message(s)
  resetConsumer: next delivery from s1

For comparison, 2.36.7 on 2.10 and 2.12 (for p in 14710 14712; do ...):

text
client v2.36.7, connected to nats-2-10, nats-server 2.10.29 (INFO)
  API level none (raw reply: no AccountInfo::$apiLevel before 2.37)
  counter stream: UnsupportedFeatureException (code 0): The "allow_msg_counter"
      feature requires NATS server 2.12+, but the connected server reports 2.10.29
      (nothing was sent: an older server ignores the field and would set up the stream
      without it), after 0.001 s
    on the server: no stream HITS
  schedule stream: UnsupportedFeatureException (code 0): The "allow_msg_schedules"
      feature requires NATS server 2.12+, but the connected server reports 2.10.29
      (nothing was sent: an older server ignores the field and would set up the stream
      without it), after 0.000 s
  atomic batch: UnsupportedFeatureException (code 0): Atomic batch publish
      requires NATS server 2.12+ (connected server 2.10.29; nothing was published),
      after 0.000 s
    on the server: BATCH exists, 0 message(s)
  resetConsumer: UnsupportedFeatureException (code 0): Consumer reset requires
      NATS server 2.14+; older servers do not answer it (connected server 2.10.29;
      nothing was sent), after 0.000 s

client v2.36.7, connected to nats-2-12, nats-server 2.12.15 (INFO)
  API level 3 (raw reply: no AccountInfo::$apiLevel before 2.37)
  counter stream: created
    on the server: HITS exists, allow_msg_counter: true, 0 message(s)
  schedule stream: created
  @every 1m: UnsupportedFeatureException (code 0): The schedule "@every 1m"
      requires NATS server 2.14+; older servers accept only "@at" schedules (connected
      server 2.12.15; nothing was published), after 0.000 s
  atomic batch: JetStreamException (code 400, err_code 10174): atomic publish is
      disabled, after 0.001 s
    on the server: BATCH exists, 0 message(s)
  resetConsumer: UnsupportedFeatureException (code 0): Consumer reset requires
      NATS server 2.14+; older servers do not answer it (connected server 2.12.15;
      nothing was sent), after 0.000 s

Every line matches the release notes' "Before upgrading" list:

  • A config field the server does not know, on a default 2.10 or 2.11: the server creates the stream without it, and then the client throws. With 2.36.7 nothing was sent and there was no stream. With 2.37.0 the stream HITS is there, without allow_msg_counter. Inspect it before you change or delete it: the message itself says it may have existed before.
  • A recurring schedule on 2.12: the server's own 400 with err_code 10189, "message schedules pattern is invalid", a plain JetStreamException. It used to be an UnsupportedFeatureException with code 0. Recurring schedules need 2.14 on the servers that hold the stream.
  • An atomic batch before 2.12: the first message is stored as a plain publish, and the call fails before the other two are sent. That is the one message in BATCH on 2.10 and 2.11, where 2.36.7 stored none. The release notes name the guard: a stream created with allow_atomic, whose create fails on such a server. On 2.12 and 2.14 our stream had no allow_atomic, so the server refused the batch itself with err_code 10174, on 2.12 with either client version.
  • A consumer reset before 2.14: older servers do not answer $JS.API.CONSUMER.RESET at all, so the call waits for the request timeout, 1.5 s here, instead of failing at once.
  • The API levels: none on 2.10, 1 on 2.11, 3 on 2.12, 4 on 2.14, as the changelog lists them.

Not run here: KV getAll() and Object Store list() now try the batched Direct Get first and fall back to one request per key when the server does not serve it, which costs one extra request on a server before 2.11.

Seven patch releases since 2.36.0

patches.php replays four of them against the same 2.14 server and the server with users, once with 2.36.0 and once with 2.37.0:

php
<?php
// patches.php: four fixes of 2.36.1 to 2.36.7. Run it on 2.36.0 and on 2.37.0.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use Amp\CancelledException;
use Amp\TimeoutCancellation;
use IDCT\NATS\Core\NatsMessage;

$client = connect('nats://127.0.0.1:14714', requestTimeoutMs: 2000); // standalone 2.14
$js = $client->jetStream();

echo "2.36.2: createStream() with 'metadata' => []\n";
try {
    fresh($js, 'META', ['meta.>'], ['metadata' => []]);
    echo "  created\n";
} catch (\Throwable $e) {
    line('  ' . failure($e));
}

echo "2.36.5: get() on a Key-Value bucket whose stream another process deleted\n";
$kv = $js->keyValue('settings');
$kv->create()->await();
$kv->put('theme', 'dark')->await();
$js->deleteStream('KV_settings')->await();
try {
    $entry = $kv->get('theme')->await();
    echo '  get(): ', $entry === null ? 'null, as for a key with no record' : 'an entry',
        "\n";
} catch (\Throwable $e) {
    line('  get(): ' . failure($e));
}

echo "2.36.3: a subject with a vertical tab, from a publisher that is not pedantic\n";
$seen = [];
$feed = $client->subscribe('feed.>', function (NatsMessage $m) use (&$seen): void {
    $seen[] = ['feed.>', $m];
})->await();
$refunds = $client->subscribe('billing.refunds', function (NatsMessage $m) use (&$seen) {
    $seen[] = ['billing.refunds', $m];
})->await();
printf("  sids: feed.> %s, billing.refunds %s\n", $feed, $refunds);
$raw = stream_socket_client('tcp://127.0.0.1:14714'); // a raw publisher, as a Go client
fgets($raw); // the server's INFO
fwrite($raw, "CONNECT {\"verbose\":false,\"pedantic\":false}\r\n"
    . "PUB feed.a\v$refunds 5\r\nhello\r\nPING\r\n");
fgets($raw); // PONG: the server has routed the message
fclose($raw);
try {
    $client->processIncoming(new TimeoutCancellation(1))->await();
} catch (CancelledException) {
    // nothing came within a second
}
foreach ($seen as [$subscription, $m]) {
    printf("  the %s handler ran: subject %s, reply %s\n", $subscription,
        json_encode($m->subject), json_encode($m->replyTo));
}
$client->disconnect()->await();

// The server with users: the worker may not pull from JOBS/audit, nor publish to svc.*.
$admin = connect('nats://127.0.0.1:14720', username: 'admin', password: 'demo');
fresh($admin->jetStream(), 'JOBS', ['jobs.>']);
$admin->jetStream()->createConsumer('JOBS', 'audit', null, ['ack_policy' => 'explicit'])
    ->await();
$admin->jetStream()->publish('jobs.1', 'a job')->await();
$admin->disconnect()->await();
$worker = connect('nats://127.0.0.1:14720', username: 'worker', password: 'demo',
    requestTimeoutMs: 2000);

echo "2.36.1: fetchBatch() from JOBS/audit, which the worker may not pull from\n";
$start = hrtime(true);
try {
    $worker->jetStream()->fetchBatch('JOBS', 'audit', 1, 1000)->await();
    echo "  a message\n";
} catch (\Throwable $e) {
    line(sprintf('  %s, after %s', failure($e), since($start)));
}

echo "2.36.7: request() to svc.a<no-break space>b, which the worker may not use\n";
$start = hrtime(true);
try {
    $worker->request("svc.a\u{00a0}b", 'ping')->await();
    echo "  a reply\n";
} catch (\Throwable $e) {
    line(sprintf('  %s, after %s', failure($e), since($start)));
}
$worker->disconnect()->await();

With 2.36.0:

text
client v2.36.0, connected to nats-2-14, nats-server 2.14.10 (INFO)
2.36.2: createStream() with 'metadata' => []
  JetStreamException (code 400, err_code 10025): invalid JSON: json: cannot
      unmarshal array into Go struct field StreamConfigRequest.StreamConfig.metadata of
      type map[string]string
2.36.5: get() on a Key-Value bucket whose stream another process deleted
  get(): null, as for a key with no record
2.36.3: a subject with a vertical tab, from a publisher that is not pedantic
  sids: feed.> 2, billing.refunds 3
  the billing.refunds handler ran: subject "feed.a", reply "2"
client v2.36.0, connected to NBG47HNG..., nats-server 2.14.10 (INFO)
client v2.36.0, connected to NBG47HNG..., nats-server 2.14.10 (INFO)
2.36.1: fetchBatch() from JOBS/audit, which the worker may not pull from
  JetStreamException (code 408): No messages received within timeout, after 2.003
      s
2.36.7: request() to svc.a<no-break space>b, which the worker may not use
  TimeoutException (code 0): Request timed out for subject svc.a b, after 2.002 s

With 2.37.0:

text
client v2.37.0, connected to nats-2-14, nats-server 2.14.10 (INFO)
2.36.2: createStream() with 'metadata' => []
  created
2.36.5: get() on a Key-Value bucket whose stream another process deleted
  get(): JetStreamException (code 404, err_code 10059): stream not found
2.36.3: a subject with a vertical tab, from a publisher that is not pedantic
  sids: feed.> 2, billing.refunds 3
  the feed.> handler ran: subject "feed.a\u000b3", reply null
client v2.37.0, connected to NBG47HNG..., nats-server 2.14.10 (INFO)
client v2.37.0, connected to NBG47HNG..., nats-server 2.14.10 (INFO)
2.36.1: fetchBatch() from JOBS/audit, which the worker may not pull from
  PermissionViolationException (code 0): The server refused the pull to
      "$JS.API.CONSUMER.MSG.NEXT.JOBS.audit": Permissions Violation for Publish to
      "$JS.API.CONSUMER.MSG.NEXT.JOBS.audit". No message was delivered for it. Grant
      this connection's user permission to publish to
      "$JS.API.CONSUMER.MSG.NEXT.JOBS.audit"., after 0.001 s
2.36.7: request() to svc.a<no-break space>b, which the worker may not use
  PermissionViolationException (code 0): The server refused the request to
      "svc.a b": Permissions Violation for Publish to "svc.a\u00a0b". No responder
      received it. Grant this connection's user permission to publish to "svc.a b".,
      after 0.000 s

What each patch release fixed, oldest first:

  • 2.36.1: a refused pull fails at once. A worker without permission to pull from a consumer used to wait out its expiry and get the 408 of an empty pull, 2.003 s here, and a loop that reads 408 as "nothing to do" ran on for ever. The changelog names symfony-nats-messenger's messenger:consume as one such loop. Now it fails with a PermissionViolationException in a millisecond. Note that it is a NatsException, not a JetStreamException: catch it where you catch the 408.
  • 2.36.2: empty metadata no longer breaks a create. PHP's [] went out as a JSON list, and every server refused the whole stream with err_code 10025. It now goes out as an object.
  • 2.36.3, security: a subject with a vertical tab reached the wrong handler. nats-server accepts such a subject from a publisher that is not pedantic, the default of nats.go and the nats CLI. 2.36.0 split the line on any whitespace, so in our run a message published to feed.a plus a vertical tab plus 3 ran the handler of billing.refunds, under the subject feed.a, with reply subject 2. Anyone who can publish into a subject space your service subscribes to with a wildcard could do this. 2.37.0 delivered it to feed.> whole. The same release fixes the README snippet issue #302 that our 2.36 post pointed out.
  • 2.36.4, security: no failover targets from plaintext. With TLS started after the server's INFO, the client used to fill its reconnect pool from the INFO read before the handshake, which an attacker on the path could rewrite. It now takes them only from an INFO received inside TLS, as nats.go v1.56.0 does. If you connect that way to a server before 2.12 with a single URL, list more than one: such a server sends no INFO inside TLS right after connecting, so there are no discovered servers until a later one.
  • 2.36.5: a read from a deleted bucket fails. Key-Value get() and getRevision(), and Object Store info(), get() and getToCallback(), returned null when the bucket's stream was gone, the same answer as for a missing key. They now throw 404 with err_code 10059, as our run shows. Code that treated that null as "bucket gone" has to catch the exception instead.
  • 2.36.6, security: discovered servers no longer choose your identity. An entry in a server's connect_urls that carried a user and password replaced your configured credentials on a failover, and behind a tls:// URL discovered servers were dialled nats://, so the credentials could go out in cleartext. A discovered server now gets the scheme and credentials of the server that listed it. A cluster behind tls:// whose peers do not offer TLS now fails over only to peers that do. We did not run 2.36.4 and 2.36.6 here: both need a planted INFO.
  • 2.36.7: a refusal is recognised when the subject has a non-printable character. nats-server writes a character Go does not count as printable, such as a no-break space, as \u00a0 in its -ERR, which 2.36.0 did not decode, so the request waited out its timeout, 2.002 s in our run. Now it fails at once.

Also in this release

The docs of diagnoseNoResponders(), NoRespondersCause and the README's "Fetch Batch" notes get two corrections. The "pulls get 503 from about 100 ms on" figure came from another run. And nats-server 2.14.10 and 2.15.3 close client connections before they stop JetStream, so a client of those releases sees its connection close and its pulls get no 503 from the stop; the docs now say which releases they describe. Since 2.36.3, pull requests no longer run Infection; the mutation job runs on main after a merge.

Quality gates

From the release notes: PHPStan level 8; 4422 unit tests (with data sets) on PHP 8.2 to 8.5; 180 live integration tests against the nats-server 2.12 fixture stack, where 7 skip because they need 2.14, and 178 in a second run against 2.14, where nothing may skip; all 52 Behat scenarios and all 47 runnable examples pass. Every changed line is covered, and total coverage is 99.11%. The change was mutation-tested on its last head before the final merge of main: a covered MSI of 92.80% against a 90% floor, with the caveat the release states itself, that 5564 of the 9589 mutants were skipped as too slow and the score does not include them.

58 unit cases in 11 test classes fail on 2.36.7's code. One of them sends 19 calls (every stream and consumer call with each gated field, a recurring schedule, schedules with source and rollup, an atomic batch and a consumer reset) to a fake server whose INFO reports an old release while its JetStream API answers as a newer one; 15 of those 19 fail on 2.36.7.

Get it

The client is free under the BSD-3-Clause license and needs PHP 8.2 or later. The php-nats-jetstream-client software page has the overview, and the source, issues and full changelog are on GitHub. If you run Symfony Messenger on NATS, the symfony-nats-messenger transport is built on this client.