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

symfony-nats-messenger 5.14: labelling streams with metadata

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

5.14.0 adds stream_metadata, from Petar Fedorovsky: the transport sets the labels it names on its stream, removes those given null and keeps every other entry. Run on NATS 2.9, 2.10 and 2.15 and on leaf nodes, plus which installs the invalid JSON fix was for.

symfony-nats-messenger 5.14.0 is out, with one new option from an outside contributor. stream_metadata, proposed by Petar Fedorovsky in #139, lets a transport put labels in the metadata of the JetStream stream it sets up: the team that owns it, a tier, a group that a tool selects streams by. It sets the entries you name, removes the ones you give null, and leaves every other entry where it is, so a label your operators' tooling wrote survives the next deploy. With the option, setup() needs NATS 2.10 or later. The release also makes the transport itself send an existing stream's metadata back as a JSON object, and our runs show which installs actually needed that.

We ran every example on PHP 8.5.9 against the official NATS images 2.9.25, 2.10.29 and 2.15.3 in Docker, with Symfony Messenger 8.2.0 and php-nats-jetstream-client 2.42.1. We installed 5.13.0 and 5.14.0 from Packagist side by side with the same composer.lock, so only the transport differs, plus two installs of 5.11.1 for the fix. The outputs are pasted as they came out.

GitHub release page of symfony-nats-messenger v5.14.0: the new stream_metadata option sets and removes entries in a stream's metadata

What stream metadata is for

Since NATS 2.10 a stream's configuration has a metadata field, a map of names to strings, and it is where people label streams. The README's examples are the team that owns a stream and the group a tool selects streams by, and operators set such entries with nats stream edit --metadata. From 2.11 on the server writes entries of its own there too, under names that start with _nats.: _nats.ver, _nats.level and _nats.req.level, the server's release and JetStream API levels.

Up to 5.13.0 the transport had no option for it. That did not mean it ignored the map: a JetStream update that leaves metadata out clears it, so on an existing stream setup() always sent the live map back as it found it. You could label a stream by hand and keep the label, but the application that owns the stream could not say anything about it in its own configuration.

The question #139 had to answer is what "the transport's metadata" means on a stream that other tools write to as well. Its answer follows two settings the transport already merges. For the subjects, the configured subject is added to the live list and nothing an operator added is removed. For the placement options, each option replaces its own field of the live block and leaves the other alone. So stream_metadata owns the entries it names and nothing else:

  • unset (null, the default), the metadata is left as it is, as before;
  • an entry you name gets your value, on a new stream and on an existing one;
  • every entry you do not name stays, whoever wrote it;
  • an entry you give null (team: ~ in YAML) is removed, whoever wrote it.

The last point is where it differs from the placement options, which cannot clear a field: clearing a placement field lets the server move the stream's replicas, while a metadata entry is only a label, and removing one moves nothing. Taking a name out of your configuration does not remove the entry. Giving it null does.

Pull request #139 on GitHub, merged: petarf-sofascore proposes stream_metadata, an option that sets or removes entries in a stream's metadata and leaves the others alone

Petar opened the pull request on 26 November with the option, its validation and the setup changes, in five commits. After several review rounds, in which our team added 19 commits on top of his, it was merged with 24, and v5.14.0 was published the same minute.

Proof of concept: labels that survive a deploy

Every example below runs on one Compose project: three servers with JetStream, one per release, and two pairs of a hub and a leaf node for the section on server versions.

yaml
# Three servers with JetStream, one per release the examples compare, and two hubs with a
# leaf node of the other release in front of each. Host ports:
#   n29      14841  nats-server 2.9.25, before stream metadata
#   n210     14842  nats-server 2.10.29, the first release with stream metadata
#   n215     14843  nats-server 2.15.3, which also writes entries of its own (_nats.)
#   hub29    14844  nats-server 2.9.25, JetStream under the domain "hub"
#   leaf215  14845  nats-server 2.15.3, leaf node of hub29, no JetStream
#   hub215   14846  nats-server 2.15.3, JetStream under the domain "hub"
#   leaf29   14847  nats-server 2.9.25, leaf node of hub215, no JetStream
services:
  n29:
    image: nats:2.9.25-alpine
    command: ["-js", "--server_name", "n29"]
    ports: ["14841:4222"]
  n210:
    image: nats:2.10.29-alpine
    command: ["-js", "--server_name", "n210"]
    ports: ["14842:4222"]
  n215:
    image: nats:2.15.3-alpine
    command: ["-js", "--server_name", "n215"]
    ports: ["14843:4222"]
  hub29:
    image: nats:2.9.25-alpine
    command: ["-c", "/etc/nats/hub.conf", "--server_name", "hub29"]
    volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
    ports: ["14844:4222"]
  leaf215:
    image: nats:2.15.3-alpine
    command: ["-c", "/etc/nats/leaf.conf", "--server_name", "leaf215"]
    environment: { HUB: "nats-leaf://hub29:7422" }
    volumes: ["./leaf.conf:/etc/nats/leaf.conf:ro"]
    ports: ["14845:4222"]
    depends_on: [hub29]
  hub215:
    image: nats:2.15.3-alpine
    command: ["-c", "/etc/nats/hub.conf", "--server_name", "hub215"]
    volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
    ports: ["14846:4222"]
  leaf29:
    image: nats:2.9.25-alpine
    command: ["-c", "/etc/nats/leaf.conf", "--server_name", "leaf29"]
    environment: { HUB: "nats-leaf://hub215:7422" }
    volumes: ["./leaf.conf:/etc/nats/leaf.conf:ro"]
    ports: ["14847:4222"]
    depends_on: [hub215]

The hubs run JetStream under the domain hub, and the leaf nodes have no JetStream of their own:

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
}
text
# leaf.conf: a leaf node of the hub in $HUB, with no JetStream of its own.
port: 4222

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

The project needs only the transport:

json
{
    "require": {
        "idct/symfony-nats-messenger": "^5.14"
    }
}

The scripts share a few helpers. api() sends one raw JetStream API request, which is what any other tool sends, the nats CLI included. labels() reads a stream's metadata back from the server and lists the server's own _nats. entries apart. setup() runs the transport's setup() and returns what happened:

php
<?php

// What the examples share. api() sends one raw JetStream API request, which is what
// any other tool (the nats CLI, Terraform, a script) sends; labels() reads a stream's
// metadata back from the server; setup() runs the transport's setup().

declare(strict_types=1);

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

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

const SERVERS = ['2.9.25' => 14841, '2.10.29' => 14842, '2.15.3' => 14843];

function client(int $port): mixed
{
    $client = (new NatsTransportConfigurationBuilder())
        ->build("nats-jetstream://127.0.0.1:$port/x/x")->client;
    $client->connect()->await();

    return $client;
}

/** One JetStream API request, its reply decoded to objects so that {} stays {}. */
function api(int $port, string $subject, ?object $body = null): object
{
    $client = client($port);
    try {
        $payload = $body === null ? '' : json_encode($body, JSON_THROW_ON_ERROR);
        $reply = $client->request('$JS.API.' . $subject, $payload)->await();

        return json_decode($reply->payload, false, 512, JSON_THROW_ON_ERROR);
    } finally {
        $client->disconnect()->await();
    }
}

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

/** The stream's metadata as the server holds it, its own _nats. entries named apart. */
function labels(int $port, string $stream): string
{
    $info = api($port, "STREAM.INFO.$stream");
    if (isset($info->error)) {
        return "no stream $stream";
    }
    $own = [];
    $servers = [];
    foreach ((array) ($info->config->metadata ?? []) as $name => $value) {
        if (str_starts_with((string) $name, '_nats.')) {
            $servers[] = "$name=$value";
        } else {
            $own[$name] = $value;
        }
    }
    ksort($own);
    sort($servers);
    $json = json_encode((object) $own, JSON_UNESCAPED_SLASHES);
    if ($servers === []) {
        return $json;
    }

    return $json . ', and the server\'s ' . implode(' ', $servers);
}

/** Runs setup() of a transport on $stream, with the DSN query and the options given. */
function setup(int $port, string $stream, array $options, string $query = ''): string
{
    $dsn = "nats-jetstream://127.0.0.1:$port/$stream/$stream.created"
        . ($query === '' ? '' : "?$query");
    try {
        $transport = new NatsTransport($dsn, $options, new PhpSerializer());
        try {
            $transport->setup();
        } finally {
            $transport->close();
        }

        return 'done';
    } catch (Throwable $e) {
        return (new ReflectionClass($e))->getShortName() . ': ' . $e->getMessage();
    }
}

/** Prints a line, wrapped under 90 characters, the indent of the next lines included. */
function out(string $line, string $indent = '    '): void
{
    echo wordwrap(rtrim($line), 88 - strlen($indent), "\n" . $indent, true), "\n";
}

labels.php takes one stream, orders, through five steps. The transport creates it with two labels from the DSN, another tool adds a label of its own through the API, and three later setups change one label, leave everything alone, and remove the other tool's label:

php
<?php

// stream_metadata on a live server. The transport labels its stream, another tool adds
// a label of its own, and later setups change, keep and remove labels.
// Run: php labels.php 14843   (nats-server 2.15.3; 14842 is 2.10.29)

declare(strict_types=1);

require __DIR__ . '/lib.php';

$port = (int) ($argv[1] ?? 14843);
versions();
api($port, 'STREAM.DELETE.orders');

$steps = [
    'setup, DSN ?stream_metadata[team]=checkout&stream_metadata[tier]=gold' =>
        fn () => setup($port, 'orders', [],
            'stream_metadata[team]=checkout&stream_metadata[tier]=gold'),
    'another tool adds backup: nightly' => function () use ($port): string {
        $config = api($port, 'STREAM.INFO.orders')->config;
        $config->metadata->backup = 'nightly';
        $reply = api($port, 'STREAM.UPDATE.orders', $config);

        return $reply->error->description ?? 'done';
    },
    'setup, stream_metadata: { tier: silver }' =>
        fn () => setup($port, 'orders', ['stream_metadata' => ['tier' => 'silver']]),
    'setup without stream_metadata' =>
        fn () => setup($port, 'orders', []),
    'setup, stream_metadata: { backup: ~ }' =>
        fn () => setup($port, 'orders', ['stream_metadata' => ['backup' => null]]),
];
$n = 0;
foreach ($steps as $what => $step) {
    out(sprintf('%d. %s: %s', ++$n, $what, $step()), '   ');
    out('   now: ' . labels($port, 'orders'), '        ');
}

Run it:

bash
docker compose up --detach
composer install
php labels.php 14843

On nats-server 2.15.3:

text
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
1. setup, DSN ?stream_metadata[team]=checkout&stream_metadata[tier]=gold: done
   now: {"team":"checkout","tier":"gold"}, and the server's _nats.level=5
        _nats.req.level=0 _nats.ver=2.15.3
2. another tool adds backup: nightly: done
   now: {"backup":"nightly","team":"checkout","tier":"gold"}, and the server's
        _nats.level=5 _nats.req.level=0 _nats.ver=2.15.3
3. setup, stream_metadata: { tier: silver }: done
   now: {"backup":"nightly","team":"checkout","tier":"silver"}, and the server's
        _nats.level=5 _nats.req.level=0 _nats.ver=2.15.3
4. setup without stream_metadata: done
   now: {"backup":"nightly","team":"checkout","tier":"silver"}, and the server's
        _nats.level=5 _nats.req.level=0 _nats.ver=2.15.3
5. setup, stream_metadata: { backup: ~ }: done
   now: {"team":"checkout","tier":"silver"}, and the server's _nats.level=5
        _nats.req.level=0 _nats.ver=2.15.3

Step 3 is the point of the option. A deploy that moves tier to silver changes tier and nothing else: backup: nightly, which the transport never heard of, stays, and so do the server's three entries. Step 4 is a configuration without the option, which is what every application had up to 5.13.0, and the map is untouched. Step 5 removes backup because the configuration names it with null. Without that, the entry would stay for as long as the stream does, as far as the transport is concerned.

On 2.10.29 (php labels.php 14842) the same five steps give the same maps, without the server's own entries, which 2.10 does not write:

text
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
1. setup, DSN ?stream_metadata[team]=checkout&stream_metadata[tier]=gold: done
   now: {"team":"checkout","tier":"gold"}
2. another tool adds backup: nightly: done
   now: {"backup":"nightly","team":"checkout","tier":"gold"}
3. setup, stream_metadata: { tier: silver }: done
   now: {"backup":"nightly","team":"checkout","tier":"silver"}
4. setup without stream_metadata: done
   now: {"backup":"nightly","team":"checkout","tier":"silver"}
5. setup, stream_metadata: { backup: ~ }: done
   now: {"team":"checkout","tier":"silver"}

An operator finds the transport's labels where they would look for them. operator.sh runs nats stream info from the nats-box image and keeps its Metadata section:

bash
#!/bin/sh
# What an operator sees of the stream "orders" with the nats CLI (nats-box 0.19.0):
# the Metadata section of "nats stream info". Run: sh operator.sh
docker run --rm --network host natsio/nats-box:0.19.0 \
  nats -s nats://127.0.0.1:14843 stream info orders \
  | sed -n '/^Metadata:/,/^State:/p' | sed '/^State:/d'
text
Metadata:

                    team: checkout
                    tier: silver

The CLI lists team and tier, and leaves the server's _nats. entries out of that section.

In a DSN, and what is refused

In a DSN each entry is stream_metadata[name]=value, the way PHP reads a map from a query string. refusals.php builds a transport configuration for a few values, before anything connects, and prints what the transport would set and remove, or why it refuses:

php
<?php

// What the transport takes as stream_metadata, and what it refuses when it is built,
// before it connects to anything. Run: php refusals.php

declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;

// [DSN query, the stream_metadata of the transport's options or null for none]
$cases = [
    ['?stream_metadata[team]=checkout&stream_metadata[tier]=gold', null],
    ['?stream_metadata[team]=', null],
    ['?stream_metadata[team]=checkout', ['tier' => 'gold']],
    ['', ['shard' => 7, 'backup' => null]],
    ['', ['_nats.ver' => '9.9.9']],
    ['', []],
    ['', ['0' => 'eu-west', '1' => 'us-east']],
    ['', ['ratio' => 1.5]],
    ['', ['blob' => str_repeat('x', 128 * 1024)]],
];

versions();
$last = null;
foreach ($cases as [$query, $map]) {
    $what = $query === '' ? '' : "DSN $query ";
    if ($map !== null) {
        $json = json_encode((object) $map);
        $what .= 'options ' . (strlen($json) > 60 ? '{"blob": 128 KiB of "x"}' : $json);
    }
    try {
        $config = (new NatsTransportConfigurationBuilder())->build(
            'nats-jetstream://127.0.0.1:14843/orders/orders.created' . $query,
            $map === null ? [] : ['stream_metadata' => $map],
        );
        $result = sprintf('sets %s, removes %s',
            json_encode((object) ($config->streamMetadata() ?? [])),
            json_encode($config->streamMetadataRemovals()));
    } catch (InvalidArgumentException $e) {
        $result = $e->getMessage() === $last ? 'refused, the same message'
            : 'refused: ' . $e->getMessage();
        $last = $e->getMessage();
    }
    out($what);
    out("  $result", '    ');
}

On 5.14.0 (php refusals.php):

text
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
DSN ?stream_metadata[team]=checkout&stream_metadata[tier]=gold
  sets {"team":"checkout","tier":"gold"}, removes []
DSN ?stream_metadata[team]=
  sets {"team":""}, removes []
DSN ?stream_metadata[team]=checkout options {"tier":"gold"}
  sets {"tier":"gold"}, removes []
options {"shard":7,"backup":null}
  sets {"shard":"7"}, removes ["backup"]
options {"_nats.ver":"9.9.9"}
  refused: The stream_metadata option cannot set "_nats.ver": NATS keeps the names
    starting with "_nats." for itself.
options {}
  refused: The stream_metadata option must be a non-empty map of non-empty names to
    strings, or to null for an entry to remove, as stream_metadata[name]=value in a DSN.
    A map whose names are exactly 0, 1, ... in that order is refused too: PHP cannot
    tell it from a list.
options {"0":"eu-west","1":"us-east"}
  refused, the same message
options {"ratio":1.5}
  refused, the same message
options {"blob": 128 KiB of "x"}
  refused: The stream_metadata option must not exceed 131072 bytes, its names and
    values together (got 131076): NATS rejects a larger map.

From the top:

  • The DSN form works, and stream_metadata[team]= is the empty string, a value NATS accepts and the transport sets. A DSN has no null, so it cannot remove an entry: removal goes through the transport's options.
  • With a map in both places, the one in options wins as a whole, as any option set in both places does: team from the DSN is not set at all. The README's advice is to keep the entries in one place.
  • An integer is written as a string, and a null value makes a name to remove.
  • Names that start with _nats. belong to the server and are refused, to set and to remove. The transport sends the server's entries back as it found them, and the server sets them again itself.
  • An empty map is refused: it would set nothing, and taking names out never removes anything.
  • So is a map whose names are exactly 0, 1 in that order. PHP holds it as a list and cannot tell it from one. Other numeric names (stream_metadata[7]=a) are fine, and so are 0 and 1 next to another name.
  • A value that is not a string, an integer or null is refused, and so is a map over 128 KiB, names and values together, which the pull request gives as the server's own limit for the whole map.

All of these are refused when the transport is built, rather than quietly left out of the stream. The same script on 5.13.0 is worth a look before a rollback:

text
symfony-nats-messenger v5.13.0, php-nats-jetstream-client v2.42.1
DSN ?stream_metadata[team]=checkout&stream_metadata[tier]=gold
  refused: Unknown option 'stream_metadata' in the DSN query of the NATS transport.
    See "Configuration Options" in the README for the options it takes.
DSN ?stream_metadata[team]=
  refused, the same message
DSN ?stream_metadata[team]=checkout options {"tier":"gold"}
  refused: Unknown option 'stream_metadata' in the options of the NATS transport.
    See "Configuration Options" in the README for the options it takes.
options {"shard":7,"backup":null}
  refused, the same message
options {"_nats.ver":"9.9.9"}
  refused, the same message
options {}
  refused, the same message
options {"0":"eu-west","1":"us-east"}
  refused, the same message
options {"ratio":1.5}
  refused, the same message
options {"blob": 128 KiB of "x"}
  refused, the same message

5.13.0 does not know the option and refuses the whole transport, from the DSN and from the options alike. A rollback to 5.13.0 with stream_metadata still in the configuration leaves every transport that has it unable to start, so take the option out first.

NATS 2.10 or later

A server before 2.10 has no stream metadata, and it does not say so. servers.php lets another tool create a stream with metadata on each of the three servers, then has the transport set up a new stream with stream_metadata:

php
<?php

// Why stream_metadata needs NATS 2.10. On each server another tool creates the stream
// "audit" with metadata, and the transport sets up a new stream "billing" with
// stream_metadata. Run: php servers.php

declare(strict_types=1);

require __DIR__ . '/lib.php';

versions();
foreach (SERVERS as $release => $port) {
    echo "nats-server $release\n";
    api($port, 'STREAM.DELETE.audit');
    api($port, 'STREAM.DELETE.billing');

    $created = api($port, 'STREAM.CREATE.audit', (object) [
        'name' => 'audit',
        'subjects' => ['audit.created'],
        'metadata' => (object) ['owner' => 'ops'],
    ]);
    out('  another tool creates audit with metadata {"owner":"ops"}: '
        . ($created->error->description ?? 'done'));
    out('    audit: ' . labels($port, 'audit'), '      ');

    $team = ['stream_metadata' => ['team' => 'billing']];
    out('  setup of billing, stream_metadata: { team: billing }: '
        . setup($port, 'billing', $team));
    out('    billing: ' . labels($port, 'billing'), '      ');
}
text
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
nats-server 2.9.25
  another tool creates audit with metadata {"owner":"ops"}: done
    audit: {}
  setup of billing, stream_metadata: { team: billing }: RuntimeException: The
    'stream_metadata' option requires NATS Server >= 2.10, but the connected server
    reports 2.9.25, which would drop it. Remove stream_metadata or upgrade NATS.
    billing: no stream billing
nats-server 2.10.29
  another tool creates audit with metadata {"owner":"ops"}: done
    audit: {"owner":"ops"}
  setup of billing, stream_metadata: { team: billing }: done
    billing: {"team":"billing"}
nats-server 2.15.3
  another tool creates audit with metadata {"owner":"ops"}: done
    audit: {"owner":"ops"}, and the server's _nats.level=5 _nats.req.level=0
      _nats.ver=2.15.3
  setup of billing, stream_metadata: { team: billing }: done
    billing: {"team":"billing"}, and the server's _nats.level=5 _nats.req.level=0
      _nats.ver=2.15.3

nats-server 2.9.25 accepted the create and dropped the map without a word: the other tool's stream has {}. That is why 5.14.0 refuses the option there instead of trusting the server. The setup fails with a message that names the server's release, and the stream billing is never created. On 2.10.29 and 2.15.3 the same setup creates billing with its label. Without the option nothing is checked, and a 2.9 server sets streams up as before.

The check reads the release of the server the transport is connected to, as scheduled_messages did up to 5.12.2 (our symfony-nats-messenger 5.13 post covers that story). On a leaf node with jetstream_domain, that is the leaf node's release, not the hub's. The README says so, and why the JetStream API level that 5.13.0 asks for schedules cannot help here: neither 2.9 nor 2.10 reports one. leaf.php runs both directions on the hubs and leaf nodes of the Compose file:

php
<?php

// stream_metadata on a leaf node with no JetStream of its own, through
// jetstream_domain=hub: the stream lives on the hub. Run: php leaf.php

declare(strict_types=1);

require __DIR__ . '/lib.php';

versions();
$cases = [
    'leaf node 2.15.3 in front of hub 2.9.25' => [14845, 14844],
    'leaf node 2.9.25 in front of hub 2.15.3' => [14847, 14846],
];
foreach ($cases as $label => [$leaf, $hub]) {
    echo "$label\n";
    api($hub, 'STREAM.DELETE.billing');
    $result = setup($leaf, 'billing', ['stream_metadata' => ['team' => 'billing']],
        'jetstream_domain=hub');
    out("  setup through the leaf node, stream_metadata: { team: billing }: $result");
    out('    on the hub, billing: ' . labels($hub, 'billing'), '      ');
}
text
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
leaf node 2.15.3 in front of hub 2.9.25
  setup through the leaf node, stream_metadata: { team: billing }: done
    on the hub, billing: {}
leaf node 2.9.25 in front of hub 2.15.3
  setup through the leaf node, stream_metadata: { team: billing }: RuntimeException:
    The 'stream_metadata' option requires NATS Server >= 2.10, but the connected server
    reports 2.9.25, which would drop it. Remove stream_metadata or upgrade NATS.
    on the hub, billing: no stream billing

A 2.15.3 leaf node in front of a 2.9.25 hub passes the check, the hub creates the stream and drops the label, and setup() reports success. A 2.9.25 leaf node in front of a 2.15.3 hub is refused, though the hub could hold the label. With leaf nodes, run 2.10 or later on both the leaf node and the hub before you turn the option on, and look at the labels on the hub after the first setup.

The fix: names that look like a list

The second change in 5.14.0 needs no option. Another tool can give a stream entries named 0 and 1, for instance one that stores a list there. PHP decodes such a map as a list, a list encodes as a JSON array, and the server's metadata is a map of strings. So a transport that read the live stream and sent it back could turn the map into an array, and the server refused the whole update with invalid JSON. On 2.11 and later the server's own _nats. entries sit next to 0 and 1, so the map stays a map there. The release notes measured the failure on 2.10.29.

numbered.php reproduces it. Another tool creates ledger with the entries 0 and 1, then the transport runs setup() on it without the option. setup() first tries a plain create. The server refuses it, because a stream of that name exists with a different configuration (the metadata), so the transport reads the live stream and sends it back as an update, map included:

php
<?php

// The fix of 5.14.0. Another tool gives the stream "ledger" a metadata map whose names
// are 0 and 1, then the transport runs setup() on it, without stream_metadata.
// Run: php numbered.php

declare(strict_types=1);

require __DIR__ . '/lib.php';

versions();
foreach (['2.10.29' => 14842, '2.15.3' => 14843] as $release => $port) {
    api($port, 'STREAM.DELETE.ledger');
    api($port, 'STREAM.CREATE.ledger', (object) [
        'name' => 'ledger',
        'subjects' => ['ledger.created'],
        'metadata' => (object) ['0' => 'eu-west', '1' => 'us-east'],
    ]);
    out("nats-server $release, another tool's ledger: " . labels($port, 'ledger'), '  ');
    out('  setup without stream_metadata: ' . setup($port, 'ledger', []));
    out('  ledger after it: ' . labels($port, 'ledger'));
}

We ran it on four installs. First 5.11.1 with php-nats-jetstream-client 2.36.1 (php numbered.php):

text
symfony-nats-messenger v5.11.1, php-nats-jetstream-client v2.36.1
nats-server 2.10.29, another tool's ledger: {"0":"eu-west","1":"us-east"}
  setup without stream_metadata: RuntimeException: Failed to setup NATS stream
    'ledger': invalid JSON
  ledger after it: {"0":"eu-west","1":"us-east"}
nats-server 2.15.3, another tool's ledger: {"0":"eu-west","1":"us-east"}, and the
  server's _nats.level=5 _nats.req.level=0 _nats.ver=2.15.3
  setup without stream_metadata: done
  ledger after it: {"0":"eu-west","1":"us-east"}, and the server's _nats.level=5
    _nats.req.level=0 _nats.ver=2.15.3

There it is on 2.10.29, and not on 2.15.3. Now the same 5.11.1 on client 2.42.1:

text
symfony-nats-messenger v5.11.1, php-nats-jetstream-client v2.42.1
nats-server 2.10.29, another tool's ledger: {"0":"eu-west","1":"us-east"}
  setup without stream_metadata: done
  ledger after it: {"0":"eu-west","1":"us-east"}
nats-server 2.15.3, another tool's ledger: {"0":"eu-west","1":"us-east"}, and the
  server's _nats.level=5 _nats.req.level=0 _nats.ver=2.15.3
  setup without stream_metadata: done
  ledger after it: {"0":"eu-west","1":"us-east"}, and the server's _nats.level=5
    _nats.req.level=0 _nats.ver=2.15.3

The failure is gone without a change to the transport. php-nats-jetstream-client 2.36.2, released on 29 November, casts a list metadata to a JSON object before it sends any stream or consumer configuration; its changelog says that nats-server 2.10 through 2.15 refused the whole create or update before that. Every transport release from 5.12.0 on requires client 2.39.1 or later, so a supported install of 5.12.0 to 5.13.0 cannot hit the failure. 5.13.0 on the same client:

text
symfony-nats-messenger v5.13.0, php-nats-jetstream-client v2.42.1
nats-server 2.10.29, another tool's ledger: {"0":"eu-west","1":"us-east"}
  setup without stream_metadata: done
  ledger after it: {"0":"eu-west","1":"us-east"}
nats-server 2.15.3, another tool's ledger: {"0":"eu-west","1":"us-east"}, and the
  server's _nats.level=5 _nats.req.level=0 _nats.ver=2.15.3
  setup without stream_metadata: done
  ledger after it: {"0":"eu-west","1":"us-east"}, and the server's _nats.level=5
    _nats.req.level=0 _nats.ver=2.15.3

And 5.14.0:

text
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
nats-server 2.10.29, another tool's ledger: {"0":"eu-west","1":"us-east"}
  setup without stream_metadata: done
  ledger after it: {"0":"eu-west","1":"us-east"}
nats-server 2.15.3, another tool's ledger: {"0":"eu-west","1":"us-east"}, and the
  server's _nats.level=5 _nats.req.level=0 _nats.ver=2.15.3
  setup without stream_metadata: done
  ledger after it: {"0":"eu-west","1":"us-east"}, and the server's _nats.level=5
    _nats.req.level=0 _nats.ver=2.15.3
Install nats-server 2.10.29 nats-server 2.15.3
5.11.1, client 2.36.1 invalid JSON set up
5.11.1, client 2.42.1 set up set up
5.13.0, client 2.42.1 set up set up
5.14.0, client 2.42.1 set up set up

What 5.14.0 changes is who keeps the map a map: the transport now sends the live metadata back as an object itself, so it no longer relies on the client for it. We checked that in copies of the 5.13.0 and 5.14.0 installs with the client's cast turned off. There 5.13.0 failed with the same invalid JSON on 2.10.29, and 5.14.0 set the stream up. The installs that could fail in practice are those of 5.11.1, the newest release whose floor still admits a client before 2.36.2, on such a client (we did not run older releases). On those, a composer update of the client or of the transport cures it.

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 section and our runs:

  • Without stream_metadata nothing changes. setup() keeps an existing stream's metadata, as it did.
  • With it, the server needs 2.10 or later, and on a leaf node with jetstream_domain the leaf node's release decides. A hub before 2.10 drops the entries behind a newer leaf node without an error.
  • Keep the entries in one place, the DSN or the options: the map in the options replaces the DSN's whole.
  • To remove a label, give it null in the options for one deploy. Deleting its line removes nothing.
  • Before a rollback to 5.13.0, take stream_metadata out of the configuration: 5.13.0 refuses a transport with an option it does not know.

How it is tested

The README now counts 1860 unit tests at about 99.8% coverage, and docs/TESTS.md keeps the mutation score of 98.6% recorded on 29 November. The option has its own Behat feature, nats_stream_metadata.feature, with five scenarios against a live server: a stream created with metadata from the DSN, configured entries set while the others stay, the metadata kept when the option is unset, an entry removed by null, and a _nats. name refused. The repository's own examples/stream-metadata.php tells the same story on the test server, and on the test cluster with a stream of three replicas whose entries are set through one server and changed through the other two. The pull request's measurements cover nats-server 2.15.2, 2.10.29 and 2.9.25.

One test fix comes with the release (#199). The JWT-expiry test with reconnect: true could see a third session under a paused process: the scripted server's delayed close ended whichever session was live 20 ms later, not the one it was armed for, and the client had already logged in again. The delayed close now ends only its own session, while that session is live.

Get it