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

php-nats-jetstream-client 2.38: typed info and subject matching

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

2.38.0 adds typed readers to StreamInfo and ConsumerInfo, and Subject::matches(), the NATS server's wildcard rules in PHP. We checked both against nats-server 2.10 to 2.15 and found where older servers disagree. Plus 2.37.1's lame duck fix.

idct/php-nats-jetstream-client 2.38.0, our free NATS and JetStream client for PHP, is out, and it adds API without changing any. StreamInfo and ConsumerInfo get typed readers for the settings and counters code most often digs out of the raw server reply, and Subject::matches() brings the NATS server's own wildcard rules into PHP: does this filter take that subject, or every subject that other filter takes?

Our last post on the client covered 2.37.0, so this one also covers 2.37.1, a patch release that changes what the client does when its server announces lame duck mode. We ran every example below on PHP 8.5.9 with 2.37.0, 2.37.1 and 2.38.0 from Packagist, against nats-server 2.10.29, 2.11.17, 2.12.15, 2.14.10 and 2.15.3 in Docker, plus two three-node 2.15.3 clusters. The output is pasted as it came out.

Why typed readers

Until 2.37, StreamInfo carried a name, the subjects and raw, the server's reply as a PHP array. ConsumerInfo had a little more, but anything else meant reading raw by hand, and the reply has traps. A consumer without a delivery limit reports max_deliver as -1, not 0 and not null. A missing field has to fall back to the server's default, and a newer server can send a policy your code has never heard of. Every caller that reads these fields has to get all of that right on its own.

Our own symfony-nats-messenger transport is one such caller. Issue #298 lists what it read from raw by hand, from max_deliver (to tell which delivery of a message is the last one) to cluster.name, and notes that it kept its own copy of the subject wildcard rules:

Issue 298 of php-nats-jetstream-client: symfony-nats-messenger reads ConsumerInfo and StreamInfo raw fields by hand and keeps its own copy of the subject wildcard rules

The issue also explains a design choice you can see in the release. The readers are methods that compute their answer from raw at every call, not new constructor properties. The transport's unit tests build these objects by hand from raw alone (the issue counts 84 new ConsumerInfo( and 32 new StreamInfo( in its tests), and a typed property filled only by fromArray() would contradict the raw of every such object. With methods, both kinds of object answer the same, and the constructors stay as they were.

GitHub release page of php-nats-jetstream-client v2.38.0: typed readers on ConsumerInfo and StreamInfo, and Subject::matches()

What 2.38.0 adds:

  • ConsumerInfo: maxDeliver() (null for no limit), filterSubjects() (filter_subject and filter_subjects in one list), ackPolicy(), deliverPolicy() and replayPolicy() (enum cases, null when missing or unknown), description(), numPending() and numAckPending().
  • StreamInfo: retention() (Limits when the field is missing, which is the server's default, and null for a policy the client does not know), replicas(), clusterName() and messages().
  • IDCT\NATS\Core\Subject::matches($filter, $subject): whether a filter takes a subject, or takes every subject another filter takes. It follows nats-server's isSubsetMatchTokenized() at v2.14.10, validates nothing and never throws.

Upgrading

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

For 2.38.0 there is nothing to do: everything is new API, and no existing method changed. The one change in behaviour since 2.37.0 comes from 2.37.1, and it only matters if you run against a cluster or a list of servers with reconnect on: the client now moves to another server when its server closes the connection at the end of lame duck mode, not when it announces it. LameDuck still fires at the announcement; Disconnected and Reconnected now come up to the grace period later (10 s by default). The section on 2.37.1 below shows both versions side by side.

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

A proof of concept you can run

Two Docker Compose projects. The first holds one standalone server per release and a three-node cluster named east:

yaml
# One standalone server per release, and a three-node cluster named "east".
name: typed-readers

x-cluster: &cluster
  image: nats:2.15.3-alpine

services:
  s210:
    image: nats:2.10-alpine     # 2.10.29
    command: [-js, -n, s210]
    ports: ["14810:4222"]
  s211:
    image: nats:2.11-alpine     # 2.11.17
    command: [-js, -n, s211]
    ports: ["14811:4222"]
  s212:
    image: nats:2.12-alpine     # 2.12.15
    command: [-js, -n, s212]
    ports: ["14812:4222"]
  s214:
    image: nats:2.14-alpine     # 2.14.10
    command: [-js, -n, s214]
    ports: ["14814:4222"]
  s215:
    image: nats:2.15.3-alpine
    command: [-js, -n, s215]
    ports: ["14815:4222"]

  c1:
    <<: *cluster
    command: [-js, -n, c1, --cluster_name, east, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://c1:6222,nats://c2:6222,nats://c3:6222"]
    ports: ["14821:4222"]
  c2:
    <<: *cluster
    command: [-js, -n, c2, --cluster_name, east, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://c1:6222,nats://c2:6222,nats://c3:6222"]
    ports: ["14822:4222"]
  c3:
    <<: *cluster
    command: [-js, -n, c3, --cluster_name, east, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://c1:6222,nats://c2:6222,nats://c3:6222"]
    ports: ["14823:4222"]

The second is a separate three-node cluster for the lame duck demo. A server in lame duck mode exits at the end of it, so restart: always brings it back for the next run, and --client_advertise makes the addresses the cluster tells the client about reachable from the host:

yaml
# Three nodes of one cluster. A server in lame duck mode exits at the end of it,
# and "restart: always" brings it back, so the demo can run again.
name: lame-duck

x-node: &node
  image: nats:2.15.3-alpine
  restart: always

services:
  l1:
    <<: *node
    command: [-js, -n, l1, --cluster_name, ldm, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://l1:6222,nats://l2:6222,nats://l3:6222",
              --client_advertise, "127.0.0.1:14831"]
    ports: ["14831:4222"]
  l2:
    <<: *node
    command: [-js, -n, l2, --cluster_name, ldm, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://l1:6222,nats://l2:6222,nats://l3:6222",
              --client_advertise, "127.0.0.1:14832"]
    ports: ["14832:4222"]
  l3:
    <<: *node
    command: [-js, -n, l3, --cluster_name, ldm, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://l1:6222,nats://l2:6222,nats://l3:6222",
              --client_advertise, "127.0.0.1:14833"]
    ports: ["14833:4222"]
json
{
    "require": {
        "php": "^8.2",
        "idct/php-nats-jetstream-client": "^2.38"
    }
}

Every script loads a few helpers. show() prints enum cases by name and lists in brackets, so the output reads the same whatever the type:

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;

/** The client version installed here, as Composer reports it. */
function clientVersion(): string
{
    $version = InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client');

    return (string) $version;
}

/** Connects to one server, quietly. */
function connect(string $url, mixed ...$options): NatsClient
{
    $client = new NatsClient(new NatsOptions(...['servers' => [$url], ...$options]));
    $client->connect()->await();

    return $client;
}

/** "s215, nats-server 2.15.3": the name and version the server's INFO reports. */
function server(NatsClient $client): string
{
    $info = $client->serverInfo();

    return sprintf('%s, nats-server %s', $info?->serverName, $info?->version);
}

/** 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();
}

/** A PHP value as it would read in JSON, enum cases by name. */
function show(mixed $value): string
{
    if ($value instanceof \UnitEnum) {
        return $value->name;
    }
    if (is_array($value) && array_is_list($value)) {
        return '[' . implode(', ', $value) . ']';
    }

    return json_encode($value, JSON_UNESCAPED_SLASHES);
}

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

The commands, in the order of this post. We ran readers.php, handmade.php and matches.php in a 2.38.0 install, and lameduck.sh in a 2.37.0 install and a 2.37.1 install:

bash
(cd servers && docker compose up -d)
(cd lame-duck && docker compose up -d)
composer install
php readers.php nats://127.0.0.1:14815
php readers.php nats://127.0.0.1:14821 3
php handmade.php
php matches.php
sh lameduck.sh

What the readers answer

readers.php creates an interest stream ORDERS with two consumers. billing takes EU and US orders through two filters, at most five deliveries each, with a description. audit takes everything, acks nothing, starts from the last message per subject and replays at the original pace, and has no delivery limit. Three orders go in, billing takes two of them without acking, and the script prints what each reader answers next to the part of the raw reply it reads:

php
<?php
// readers.php: what the new readers of StreamInfo and ConsumerInfo answer, next to
// the part of the raw reply they read. Usage: php readers.php URL [replicas]
declare(strict_types=1);

require __DIR__ . '/lib.php';

$client = connect($argv[1]);
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), PHP_EOL;

fresh($js, 'ORDERS', ['orders.>'], [
    'retention' => 'interest',
    'num_replicas' => (int) ($argv[2] ?? 1),
]);
$js->createConsumer('ORDERS', 'billing', null, [
    'filter_subjects' => ['orders.eu.*', 'orders.us.*'],
    'max_deliver' => 5,
    'description' => 'EU and US invoices',
])->await();
$js->createConsumer('ORDERS', 'audit', 'orders.>', [
    'ack_policy' => 'none',
    'deliver_policy' => 'last_per_subject',
    'replay_policy' => 'original',
])->await();
foreach (['eu.1001', 'us.1002', 'ap.1003'] as $order) {
    $js->publish("orders.$order", 'an order')->await();
}
$js->fetchBatch('ORDERS', 'billing', 2, 1000)->await(); // taken, not acked yet

$stream = $js->getStream('ORDERS')->await();
printf("  ORDERS   retention() %s, replicas() %d, messages() %d\n",
    show($stream->retention()), $stream->replicas(), $stream->messages());
$keys = implode(', ', array_keys($stream->raw['cluster'] ?? []));
echo wordwrap(sprintf('           clusterName() %s; raw cluster has {%s}',
    show($stream->clusterName()), $keys), 80, "\n" . str_repeat(' ', 11)), PHP_EOL;

foreach (['billing', 'audit'] as $name) {
    $consumer = $js->getConsumer('ORDERS', $name)->await();
    printf("  %-8s maxDeliver() %s; raw max_deliver %s\n", $name,
        show($consumer->maxDeliver()), show($consumer->raw['config']['max_deliver']));
    printf("           filterSubjects() %s\n", show($consumer->filterSubjects()));
    printf("           ackPolicy() %s, deliverPolicy() %s, replayPolicy() %s\n",
        show($consumer->ackPolicy()), show($consumer->deliverPolicy()),
        show($consumer->replayPolicy()));
    printf("           description() %s, numPending() %d, numAckPending() %d\n",
        show($consumer->description()), $consumer->numPending(),
        $consumer->numAckPending());
}

$js->deleteStream('ORDERS')->await();
$client->disconnect()->await();

On the standalone 2.15.3 server:

text
s215, nats-server 2.15.3, client v2.38.0
  ORDERS   retention() Interest, replicas() 1, messages() 3
           clusterName() null; raw cluster has {leader}
  billing  maxDeliver() 5; raw max_deliver 5
           filterSubjects() [orders.eu.*, orders.us.*]
           ackPolicy() Explicit, deliverPolicy() All, replayPolicy() Instant
           description() "EU and US invoices", numPending() 0, numAckPending() 2
  audit    maxDeliver() null; raw max_deliver -1
           filterSubjects() [orders.>]
           ackPolicy() None, deliverPolicy() LastPerSubject, replayPolicy() Original
           description() null, numPending() 3, numAckPending() 0

On the cluster, with three replicas (php readers.php nats://127.0.0.1:14821 3):

text
c1, nats-server 2.15.3, client v2.38.0
  ORDERS   retention() Interest, replicas() 3, messages() 3
           clusterName() "east"; raw cluster has {name, raft_group, leader,
           leader_since, system_account, traffic_account, replicas}
  billing  maxDeliver() 5; raw max_deliver 5
           filterSubjects() [orders.eu.*, orders.us.*]
           ackPolicy() Explicit, deliverPolicy() All, replayPolicy() Instant
           description() "EU and US invoices", numPending() 0, numAckPending() 2
  audit    maxDeliver() null; raw max_deliver -1
           filterSubjects() [orders.>]
           ackPolicy() None, deliverPolicy() LastPerSubject, replayPolicy() Original
           description() null, numPending() 3, numAckPending() 0
  • No limit is null, not -1. audit was created without max_deliver, and the server reports -1. maxDeliver() answers null, so if ($consumer->maxDeliver() !== null) is the whole check.
  • Two filters, one list. filterSubjects() returns billing's two filters and audit's single filter_subject in the same shape, so code that asks "which subjects does this consumer take" no longer cares which field the server used.
  • Policies are enum cases. ackPolicy(), deliverPolicy() and replayPolicy() return AckPolicy, DeliverPolicy and ReplayPolicy cases you can compare with === and match.
  • The counters are what you would expect. billing holds two orders that were delivered and not acked, and the third order, orders.ap.1003, is not one of its subjects, so it has 0 pending and 2 waiting for an ack. audit has all three still to deliver.
  • replicas() and clusterName() tell a cluster from a single server. 3 and "east" on the cluster, 1 and null on the standalone server.

One detail the output shows that the code does not say: a single server does send a cluster object, with its leader and nothing else. The docblock of clusterName() at 2.38.0 says a single server sends no cluster at all. The changelog has it right, the answer is null either way, and the docblock fix is tracked in issue #318. We checked the other four releases too:

bash
for p in 14810 14811 14812 14814; do php readers.php nats://127.0.0.1:$p; done \
  | grep -E '^s|ORDERS|raw'
text
s210, nats-server 2.10.29, client v2.38.0
  ORDERS   retention() Interest, replicas() 1, messages() 3
           clusterName() null; raw cluster has {leader}
  billing  maxDeliver() 5; raw max_deliver 5
  audit    maxDeliver() null; raw max_deliver -1
s211, nats-server 2.11.17, client v2.38.0
  ORDERS   retention() Interest, replicas() 1, messages() 3
           clusterName() null; raw cluster has {leader}
  billing  maxDeliver() 5; raw max_deliver 5
  audit    maxDeliver() null; raw max_deliver -1
s212, nats-server 2.12.15, client v2.38.0
  ORDERS   retention() Interest, replicas() 1, messages() 3
           clusterName() null; raw cluster has {leader}
  billing  maxDeliver() 5; raw max_deliver 5
  audit    maxDeliver() null; raw max_deliver -1
s214, nats-server 2.14.10, client v2.38.0
  ORDERS   retention() Interest, replicas() 1, messages() 3
           clusterName() null; raw cluster has {leader}
  billing  maxDeliver() 5; raw max_deliver 5
  audit    maxDeliver() null; raw max_deliver -1

Same answers from 2.10.29 to 2.14.10: the cluster object with leader only, and -1 for no delivery limit.

Objects built by hand

The readers are meant to give the same answer for an object you build yourself, as unit tests do, and to fall back to a default instead of failing when a field is missing or odd. handmade.php builds a few such objects with no server involved:

php
<?php
// handmade.php: info objects built by hand from raw alone, the way unit tests
// build them. No server involved.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\JetStream\Models\ConsumerInfo;
use IDCT\NATS\JetStream\Models\StreamInfo;

$streams = [
    'no retention field' => [],
    'retention "workqueue"' => ['retention' => 'workqueue'],
    'retention "some_future_policy"' => ['retention' => 'some_future_policy'],
    'num_replicas 0' => ['num_replicas' => 0],
];
foreach ($streams as $label => $config) {
    $stream = new StreamInfo('JOBS', ['jobs.>'], ['config' => $config]);
    printf("%-32s retention() %s, replicas() %d\n", $label,
        show($stream->retention()), $stream->replicas());
}

$consumer = new ConsumerInfo('JOBS', 'worker', false, [
    'config' => [
        'max_deliver' => 0,
        'filter_subject' => '',
        'filter_subjects' => ['jobs.resize', 7, '', 'jobs.thumbnail'],
        'ack_policy' => 'explicit',
        'replay_policy' => 'some_future_replay',
    ],
    'num_pending' => '12',
]);
printf("consumer worker: maxDeliver() %s, filterSubjects() %s\n",
    show($consumer->maxDeliver()), show($consumer->filterSubjects()));
printf("                 ackPolicy() %s, replayPolicy() %s, numPending() %d\n",
    show($consumer->ackPolicy()), show($consumer->replayPolicy()),
    $consumer->numPending());
text
no retention field               retention() Limits, replicas() 1
retention "workqueue"            retention() WorkQueue, replicas() 1
retention "some_future_policy"   retention() null, replicas() 1
num_replicas 0                   retention() Limits, replicas() 1
consumer worker: maxDeliver() null, filterSubjects() [jobs.resize, jobs.thumbnail]
                 ackPolicy() Explicit, replayPolicy() null, numPending() 0
  • A missing retention reads as Limits, the server's default.
  • An unknown policy reads as null, not as Limits. That is deliberate: if a future server adds a retention policy, code that branches on retention() sees "I do not know this one" instead of a wrong answer. The same holds for replayPolicy() with an unknown value.
  • The defaults are spelled out. num_replicas 0 reads as 1 replica, max_deliver 0 as no limit, and filterSubjects() drops the integer and the empty strings. A counter sent as the string '12' reads as 0: the changelog says so, because the server sends JSON numbers.

Subject::matches() against five servers

A NATS subject is a list of tokens separated by dots. In a filter, * takes exactly one token and > takes one token or more, at the end. That much is common knowledge. The corners are less so: a * inside a longer token, as in foo.*bar, is a plain character, and a filter can be compared with another filter, not only with a subject. foo.> takes every subject foo.* takes, but not the other way round. Subject::matches() answers both questions with one method, as the server does with one function.

We did not want to take the docblock's word for it, so matches.php puts each answer next to what five server releases do with the same pair. Part 1 compares a filter with a literal subject: a stream holds one message on the subject, a consumer is created with the filter, and the server's num_pending says whether the consumer will get it. Part 2 compares two filters. A consumer may have several filter_subjects, and the server refuses them with err_code 10138 when they "overlap":

php
<?php
// matches.php: Subject::matches() next to what five nats-server releases do with
// the same pair of subjects.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Core\Subject;
use IDCT\NATS\Exception\JetStreamException;

$servers = [];
foreach ([14810, 14811, 14812, 14814, 14815] as $port) {
    $client = connect("nats://127.0.0.1:$port");
    $servers[$client->serverInfo()?->version] = $client->jetStream();
}
$row = function (string ...$cells): string {
    $line = vsprintf('%-10s %-11s %-10s', $cells);
    foreach (array_slice($cells, 3) as $cell) {
        $line .= sprintf(' %-7s', $cell);
    }

    return rtrim($line);
};

// 1. A filter and a literal subject. A consumer with the filter is created on a stream
//    that holds one message on the subject: does the server count it as pending?
echo "1. does a consumer with this filter get a message on this subject?\n";
echo $row('filter', 'subject', 'matches()', ...array_keys($servers)), PHP_EOL;
$pairs = [
    ['foo.*', 'foo.bar'], ['foo.*', 'foo.bar.baz'], ['foo.>', 'foo.bar.baz'],
    ['foo.>', 'foo'], ['*.bar', 'foo.baz'], ['foo.*.baz', 'foo.x.baz'],
    ['foo.*bar', 'foo.xbar'], ['>', 'foo'],
];
foreach ($pairs as [$filter, $subject]) {
    $answers = [];
    foreach ($servers as $js) {
        fresh($js, 'PAIRS', ['foo', 'foo.>']);
        $js->publish($subject, 'x')->await();
        $consumer = $js->createConsumer('PAIRS', 'probe', $filter)->await();
        $answers[] = $consumer->numPending() === 1 ? 'yes' : 'no';
    }
    $matches = show(Subject::matches($filter, $subject));
    echo $row($filter, $subject, $matches, ...$answers), PHP_EOL;
}

// 2. Two filters. The server refuses a consumer whose filter_subjects overlap (err_code
//    10138). What counts as an overlap?
echo "\n2. does the server refuse filter_subjects [A, B] as overlapping?\n";
echo str_pad($row('A', 'B', 'A takes B', ...array_keys($servers)), 73), '  B takes A',
    PHP_EOL;
$pairs = [
    ['foo.>', 'foo.*'], ['foo.*.baz', 'foo.>'], ['foo.bar', 'foo.*'],
    ['foo.*', 'foo.*bar'], ['foo.*.*', 'foo.>'], ['foo.*', '*.bar'],
];
foreach ($pairs as [$a, $b]) {
    $answers = [];
    foreach ($servers as $js) {
        fresh($js, 'PAIRS', ['foo', 'foo.>']);
        try {
            $js->createConsumer('PAIRS', 'probe', null, ['filter_subjects' => [$a, $b]])
                ->await();
            $answers[] = 'accepts';
        } catch (JetStreamException $e) {
            $answers[] = (string) $e->getErrCode();
        }
    }
    echo str_pad($row($a, $b, show(Subject::matches($a, $b)), ...$answers), 73),
        '  ', show(Subject::matches($b, $a)), PHP_EOL;
}
foreach ($servers as $js) {
    $js->deleteStream('PAIRS')->await();
}
text
1. does a consumer with this filter get a message on this subject?
filter     subject     matches()  2.10.29 2.11.17 2.12.15 2.14.10 2.15.3
foo.*      foo.bar     true       yes     yes     yes     yes     yes
foo.*      foo.bar.baz false      no      no      no      no      no
foo.>      foo.bar.baz true       yes     yes     yes     yes     yes
foo.>      foo         false      no      no      no      no      no
*.bar      foo.baz     false      no      no      no      no      no
foo.*.baz  foo.x.baz   true       yes     yes     yes     yes     yes
foo.*bar   foo.xbar    false      no      no      no      no      no
>          foo         true       yes     yes     yes     yes     yes

2. does the server refuse filter_subjects [A, B] as overlapping?
A          B           A takes B  2.10.29 2.11.17 2.12.15 2.14.10 2.15.3   B takes A
foo.>      foo.*       true       10138   10138   10138   10138   10138    false
foo.*.baz  foo.>       false      10138   10138   10138   10138   10138    true
foo.bar    foo.*       false      10138   10138   10138   10138   10138    true
foo.*      foo.*bar    true       10138   10138   10138   10138   10138    false
foo.*.*    foo.>       false      10138   10138   10138   10138   10138    true
foo.*      *.bar       false      10138   10138   accepts accepts accepts  false
  • Part 1: matches() agrees with every server on every row. That includes foo.*bar as a literal token, foo.> not taking foo (a > needs at least one token) and a bare > taking foo. The release notes add that in the review matches() was compared with a line-by-line transcription of the server's function over 341,056 filter and subject pairs, with no difference.
  • Part 2, the first five rows: a subset is refused everywhere. Whenever one filter takes every subject of the other, in either direction, all five releases refuse the consumer.
  • Part 2, the last row is the one to remember. foo.* and *.bar share a subject, foo.bar, but neither takes every subject of the other. nats-server 2.10.29 and 2.11.17 refuse the pair; 2.12.15, 2.14.10 and 2.15.3 accept it. This is not in the release notes; we found it here and then read the server's consumer.go at several tags. In 2.11.17 and in 2.12.0 to 2.12.4 the check calls SubjectsCollide(), which asks whether two filters share any subject. From 2.12.5 on it calls subjectIsSubsetMatch(), the function matches() follows.

So matches() answers "does A take B", which is the question newer servers ask. If you need to predict whether a 2.10 or 2.11 server will refuse a set of filters, checking matches() both ways is not enough: two filters can share subjects without either taking the other.

What it is for in practice: before publishing to a subject, or before relying on a consumer to see it, check the subject against each of the consumer's filterSubjects() with Subject::matches(). That is the check symfony-nats-messenger makes when it asks whether a consumer of an interest stream takes its delayed messages; the transport's switch to the new API is a later step of its issue #129. Note that matches() validates nothing: the changelog says a filter like foo.*bar, which the server accepts but the client's own subject check would refuse, still gets the server's answer.

2.37.1: a lame-duck notice no longer moves the client

A NATS server that is about to be stopped or upgraded can enter lame duck mode. It tells its clients with an INFO message carrying "ldm": true, keeps their connections open for a grace period (10 s by default) and then closes them. Since #47, this client moved to another server at the notice whenever it knew more than one. The trouble is the reply that was already on its way. Adrian Brajković reported it in issue #265, with a reproduction on client 2.30.1 and nats-server 2.15.0:

Issue 265 opened by Brajk19: when the connected server enters lame duck mode, the next request fails with TimeoutException although the server stored the message

We rebuilt his test. The client is given l1 only and learns about l2 and l3 from the cluster. It publishes to a three-replica stream every 50 ms for 20 s, with a 2 s request timeout instead of the default 10 s, and prints every connection event and every failure:

php
<?php
// lameduck.php: a JetStream publish every 50 ms for 20 s, given l1 only. lameduck.sh
// puts l1 into lame duck mode 3 s in.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Connection\Enum\ConnectionEvent;

use function Amp\delay;

$start = hrtime(true);
$client = null;
$events = function (ConnectionEvent $event) use (&$client, $start): void {
    if ($event === ConnectionEvent::Reconnected) {
        printf("%s  Reconnected, now on %s\n", since($start),
            $client->serverInfo()?->serverName);
    } elseif ($event !== ConnectionEvent::DiscoveredServers) {
        printf("%s  %s\n", since($start), $event->name);
    }
};
$client = connect('nats://127.0.0.1:14831', requestTimeoutMs: 2000,
    connectionListener: $events);
$js = $client->jetStream();
fresh($js, 'LDM', ['ldm.>'], ['num_replicas' => 3]);
printf("%s  client %s on %s, stream LDM with 3 replicas\n", since($start),
    clientVersion(), server($client));

$acked = 0;
for ($i = 1; hrtime(true) - $start < 20e9; $i++) {
    $sent = hrtime(true);
    try {
        $js->publish('ldm.test', "message $i")->await();
        $acked++;
    } catch (\Throwable $e) {
        printf("%s  publish #%d failed after %s: %s\n", since($start), $i,
            trim(since($sent)), (new \ReflectionClass($e))->getShortName());
    }
    delay(0.05);
}
$stored = $js->getStream('LDM')->await()->raw['state']['messages'];
printf("%s  %d publishes, %d acked, the stream holds %d\n", since($start), $i - 1,
    $acked, $stored);
$client->disconnect()->await();

lameduck.sh puts l1 into lame duck mode three to four seconds in, with the server's own --signal ldm inside its container:

bash
#!/bin/sh
# lameduck.sh: runs lameduck.php and puts l1 into lame duck mode 3 s later.
php lameduck.php &
sleep 3
docker exec lame-duck-l1-1 nats-server --signal ldm=1
wait

With 2.37.0:

text
 0.009 s  Connected
 0.100 s  client v2.37.0 on l1, nats-server 2.15.3, stream LDM with 3 replicas
 4.054 s  LameDuck
 4.054 s  Disconnected
 4.061 s  Reconnected, now on l3
 6.056 s  publish #73 failed after 2.002 s: TimeoutException
20.021 s  343 publishes, 342 acked, the stream holds 343
20.021 s  Closed

With 2.37.1:

text
 0.009 s  Connected
 0.096 s  client v2.37.1 on l1, nats-server 2.15.3, stream LDM with 3 replicas
 3.033 s  LameDuck
13.056 s  Disconnected
13.062 s  Reconnected, now on l3
20.001 s  387 publishes, 387 acked, the stream holds 387
20.002 s  Closed
  • 2.37.0 left at the notice and lost a reply. LameDuck, Disconnected and Reconnected came within 7 ms, and the publish sent just as the notice arrived failed after the full 2 s timeout. The stream holds 343 messages, one more than were acked: the server stored that message, but its acknowledgement went down with the socket the client had just closed. A retry without a message ID would store it twice.
  • 2.37.1 stayed on l1 for the grace period. LameDuck at 3.0 s, then nothing for 10 s, while every publish went on through l1. Disconnected came at 13.1 s, when the server closed the connection, and the client was on l3 6 ms later. 387 publishes, 387 acked, 387 stored.

That is what the release notes measured too, on a three-node 2.15.2 cluster: one publish lost to a timeout before the fix and none after, and a reconnect under 10 ms at the server's close. They also measured a pull: before the fix, a fetch of one message that read the notice ended with a 408 and its message came back only after ack_wait. We did not run that one. The nats.go, nats.java, nats.js and nats.py clients do not move at the notice either, the release notes say.

Two things to know before you upgrade. If your code waited for Disconnected to react to a rollout early, that event now comes at the close, up to the grace period later; listen for LameDuck instead. And on servers released before 2.14.10 and 2.15.3, lame duck mode stops JetStream before it tells the clients, so a pull on the connection that now stays gets a 503 until the server closes it, and a pull loop has to pause between pulls (the README's "Fetch Batch" notes cover it). We ran the demo on 2.15.3, which keeps JetStream running through lame duck mode.

Adrian also tested the fix himself and confirmed on the issue that it works as expected. Thank you, Adrian: a reproduction like yours is the fastest way to a fix.

Quality gates

From the 2.38.0 release notes: PHPStan level 8; 4394 unit tests (with data sets) on PHP 8.2 to 8.5, 104 more than in 2.37.1 and all of them for the new readers and Subject::matches(); 181 live integration tests against the nats-server 2.12 fixture stack, 7 of them skipped there because they need 2.14, and 179 in a second run against 2.14, where nothing may skip. The new ModelReadersIntegrationTest also passed against nats-server 2.10.29, 2.11.17, 2.12.15, 2.14.10 and 2.15.3 in the review. All 52 Behat scenarios and all 47 runnable examples pass, every changed line is covered and total coverage is 99.08%. The change was mutation-tested before its last merge of main: a covered MSI of 92.94% against a 90% floor, with the caveat the release states itself, that 5378 of the 9726 mutants were skipped as too slow and the score does not include them.

For 2.37.1: 4290 unit tests, 132 fewer than in 2.37.0 because the failover's own tests went with it, and a new LameDuckNoticeKeepsTheConnectionTest whose 5 cases all fail on 2.37.0's code.

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, and the readers in this release were asked for on its behalf.