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

php-nats-jetstream-client 2.43: your connection's account

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

2.43.0 adds remoteAccount(), isSystemAccount(), clientId() and clientIp(): what nats-server knows about your connection. We ran them on nats-server 2.11 to 2.15 with named accounts, a late INFO, a forged greeting and a reconnect into another account. Plus 2.42.1.

idct/php-nats-jetstream-client 2.43.0, our free NATS and JetStream client for PHP, adds four methods that say what the server knows about your connection: remoteAccount(), the account the connection landed in; isSystemAccount(), whether that is the server's system account; clientId(), the connection's id on the server; and clientIp(), your address as the server sees it. nats-server has sent these values for a while. Until this release the client read past them.

Our last post covered 2.42.0, and 2.42.1, an internal change, came out between the two; it is at the end. We ran every example below on PHP 8.5.9 with 2.43.0 from Packagist, against nats-server 2.11.17, 2.12.15 and 2.15.3 in Docker, with named accounts, a system account and a small PHP proxy that changes how the server's INFO reaches the client. The output is pasted as it came out.

Why a client wants to know its account

In NATS an account is a wall. Subjects, streams, Key-Value buckets and services of one account are invisible to another unless one exports them and the other imports them. Which account a connection lands in is decided by the server, from the credentials (user and password, a JWT, an NKey) and the server's configuration. The client never chose it, and until now a PHP client could not ask.

That matters when something is off. A worker started with the credentials of another account connects without an error, then sees no messages and gets "no responders" on every request. A process running in the system account can read the server's internal $SYS subjects, which application code should never touch. And after a reconnect, the new server may map the same credentials to a different account. Issue #343, the brief for this release, put it plainly: ServerInfo dropped remote_account, acc_is_sys, client_id and client_ip, so the client could not tell which account a connection was bound to, while nats.go v1.55.0 already had Conn.RemoteAccount().

GitHub release page of php-nats-jetstream-client v2.43.0: remoteAccount(), isSystemAccount(), clientId() and clientIp() on NatsClient and NatsConnection

What 2.43.0 adds, on both NatsClient and NatsConnection:

  • remoteAccount(): the account's name as nats-server knows it, or null. A server without accounts says $G, its global account.
  • isSystemAccount(): true when that account is the server's system account.
  • clientId(): the connection's id, the cid that the server's connz monitoring, its $SYS events and its log use.
  • clientIp(): the address the server sees the connection coming from.
  • ServerInfo gets the same four as properties (remoteAccount, isSystemAccount, clientId, clientIp), added as optional last constructor parameters. A value that is missing or of the wrong type reads as null, or as false for the flag.

The account needs nats-server 2.12 or later. The id and the address come from every INFO the server sends, so they work on older servers too.

Upgrading

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

There is nothing to change in existing code. Code that builds ServerInfo itself, such as tests and doubles, keeps working, because the four new parameters come last and are optional. Require ^2.43 in composer.json when your code calls the new methods. The only other change in 2.43.0 is in CI: PHPStan 2.4.0, which CI installs fresh because the repository pins no lock file, reported 6 errors in unchanged code; a stub file that only PHPStan reads and two small code edits fix that, with no change in behaviour.

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

A proof of concept you can run

One Docker Compose project: a server without accounts per release we ran, the same three accounts on 2.11, 2.12 and 2.15, and a second 2.15 server where the user app belongs to another account.

yaml
# The servers of the 2.43 examples: one without accounts per release we ran,
# the same accounts on 2.11, 2.12 and 2.15, and a server where "app" is in TARGET.
name: conn-account

services:
  s211:
    image: nats:2.11.17-alpine
    command: [-n, s211]
    ports: ["15431:4222"]
  s212:
    image: nats:2.12-alpine     # 2.12.15
    command: [-n, s212]
    ports: ["15432:4222"]
  s215:
    image: nats:2.15.3-alpine
    command: [-n, s215, -m, "8222"]
    ports: ["15435:4222", "15445:8222"]
  acc211:
    image: nats:2.11.17-alpine
    command: [-c, /etc/nats/accounts.conf, -n, acc211]
    volumes: ["./accounts.conf:/etc/nats/accounts.conf:ro"]
    ports: ["15439:4222"]
  acc212:
    image: nats:2.12-alpine     # 2.12.15
    command: [-c, /etc/nats/accounts.conf, -n, acc212]
    volumes: ["./accounts.conf:/etc/nats/accounts.conf:ro"]
    ports: ["15438:4222"]
  acc:
    image: nats:2.15.3-alpine
    command: [-c, /etc/nats/accounts.conf]
    volumes: ["./accounts.conf:/etc/nats/accounts.conf:ro"]
    ports: ["15436:4222", "15446:8222"]
  moved:
    image: nats:2.15.3-alpine
    command: [-c, /etc/nats/moved.conf]
    volumes: ["./moved.conf:/etc/nats/moved.conf:ro"]
    ports: ["15437:4222"]
text
# Accounts for the 2.43 examples: two application accounts and a system account.
server_name: acc
http_port: 8222

accounts: {
  ORIGIN: {
    users: [
      { user: a, password: a }
      { user: app, password: app }
      { user: lim, password: lim, permissions: { publish: { deny: ["secret.>"] } } }
    ]
  }
  TARGET: {
    users: [ { user: b, password: b } ]
  }
  SYS: {
    users: [ { user: sys, password: sys } ]
  }
}
system_account: SYS
text
# A second server where the user "app" belongs to another account, TARGET.
server_name: moved

accounts: {
  TARGET: {
    users: [ { user: app, password: app } ]
  }
  SYS: {
    users: [ { user: sys, password: sys } ]
  }
}
system_account: SYS
json
{
    "require": {
        "php": "^8.2",
        "idct/php-nats-jetstream-client": "^2.43"
    }
}

Every script loads three helpers: client() builds a client from a URL with the user and password in it, seen() prints the account and the system flag, and since() the time since a start:

php
<?php
// lib.php: helpers shared by the 2.43 examples.
declare(strict_types=1);

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

use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;

/** A client for nats://[user:password@]host:port, with any other NatsOptions. */
function client(string $url, mixed ...$options): NatsClient
{
    $u = parse_url($url);
    return new NatsClient(new NatsOptions(...[
        'servers' => [sprintf('nats://%s:%d', $u['host'], $u['port'])],
        'username' => $u['user'] ?? null,
        'password' => $u['pass'] ?? null,
        ...$options,
    ]));
}

/** What the client knows about its connection, as one short line. */
function seen(NatsClient $c): string
{
    return sprintf('%-7s %-5s', $c->remoteAccount() ?? 'null',
        $c->isSystemAccount() ? 'true' : 'false');
}

/** Seconds since $t0, with millisecond precision. */
function since(float $t0): string
{
    return sprintf('%6.3f s', hrtime(true) / 1e9 - $t0);
}

The commands, in the order of this post, all in one 2.43.0 install:

bash
(cd servers && docker compose up -d)
composer install
php info-proxy.php 15451 127.0.0.1:15435 late 300 60 &
php info-proxy.php 15452 127.0.0.1:15431 forge 0 60 &
php info-proxy.php 15453 127.0.0.1:15436 forge 0 60 &
php wire.php 127.0.0.1:15431
php wire.php 127.0.0.1:15435
php wire.php 127.0.0.1:15436 sys sys
php whoami.php s211=nats://127.0.0.1:15431 s212=nats://127.0.0.1:15432 \
  s215=nats://127.0.0.1:15435 'acc211 a=nats://a:[email protected]:15439' \
  'acc212 a=nats://a:[email protected]:15438' 'acc a=nats://a:[email protected]:15436' \
  'acc b=nats://b:[email protected]:15436' 'acc sys=nats://sys:[email protected]:15436'
php guard.php nats://a:[email protected]:15436 ORIGIN; echo "exit $?"
php guard.php nats://sys:[email protected]:15436 ORIGIN; echo "exit $?"
php guard.php nats://b:[email protected]:15436 ORIGIN; echo "exit $?"
php guard.php nats://a:[email protected]:15439 ORIGIN; echo "exit $?"
php late.php nats://127.0.0.1:15435
php late.php nats://127.0.0.1:15451
php wire.php 127.0.0.1:15453 a a
php whoami.php s211=nats://127.0.0.1:15452 'acc a=nats://a:[email protected]:15453'
php connz.php nats://app:[email protected]:15436 http://127.0.0.1:15446
php reconnect.php 127.0.0.1:15436 127.0.0.1:15437 nats://sys:[email protected]:15436
php refused.php nats://lim:[email protected]:15436

What the server says

Before any client library, the wire. wire.php opens a plain socket, reads the server's greeting, sends CONNECT and PING, and prints every line the server sends in the next 300 ms, keeping only the INFO fields about the connection itself:

php
<?php
// wire.php: what a server says to a new connection, with no client library.
// php wire.php <host:port> [user] [password]
// Reads the greeting INFO, sends CONNECT and PING, then prints every line the
// server sends in the next 300 ms. Of an INFO it prints only the fields about
// the connection itself.
declare(strict_types=1);

[, $addr] = $argv;
$user = $argv[2] ?? null;
$pass = $argv[3] ?? null;
$keys = ['server_name', 'version', 'connect_info', 'client_id', 'client_ip',
    'remote_account', 'acc_is_sys'];

function show(string $line, array $keys): void
{
    if (!str_starts_with($line, 'INFO ')) {
        echo '  <- ', $line, PHP_EOL;
        return;
    }
    $info = json_decode(substr($line, 5), true);
    $pairs = [];
    foreach (array_intersect_key($info, array_flip($keys)) as $key => $value) {
        $pairs[] = $key . '=' . json_encode($value, JSON_UNESCAPED_SLASHES);
    }
    echo '  <- INFO ', wordwrap(implode(' ', $pairs), 76, "\n          "), PHP_EOL;
}

$s = stream_socket_client("tcp://$addr", $errno, $error, 2.0);
show(rtrim(fgets($s)), $keys);
$connect = ['verbose' => false, 'pedantic' => false, 'protocol' => 1,
    'headers' => true, 'name' => 'wire.php'];
if ($user !== null) {
    $connect += ['user' => $user, 'pass' => $pass];
}
fwrite($s, 'CONNECT ' . json_encode($connect) . "\r\nPING\r\n");
echo "  -> CONNECT, PING\n";
stream_set_timeout($s, 0, 300_000);
while (($line = fgets($s)) !== false) {
    show(rtrim($line), $keys);
}
fclose($s);

nats-server 2.11.17:

text
  <- INFO server_name="s211" version="2.11.17" client_id=11 client_ip="172.20.0.1"
  -> CONNECT, PING
  <- PONG

nats-server 2.15.3, no accounts:

text
  <- INFO server_name="s215" version="2.15.3" client_id=17 client_ip="172.20.0.1"
  -> CONNECT, PING
  <- PONG
  <- INFO server_name="s215" version="2.15.3" client_id=17 client_ip="172.20.0.1"
          connect_info=true remote_account="$G"

nats-server 2.15.3, as the user sys of the system account:

text
  <- INFO server_name="acc" version="2.15.3" client_id=65 client_ip="172.20.0.1"
  -> CONNECT, PING
  <- PONG
  <- INFO server_name="acc" version="2.15.3" client_id=65 client_ip="172.20.0.1"
          connect_info=true remote_account="SYS" acc_is_sys=true
  • The greeting carries the id and the address on every release, 2.11 included. That is why clientId() and clientIp() work everywhere.
  • From 2.12, a second INFO follows the PONG. It is marked connect_info=true and names the account. 2.11 sends nothing after the PONG.
  • acc_is_sys appears only when it is true. The 2.15.3 answer without accounts leaves it out, so a missing field means false.
  • The address is the one the server sees. Here every connection came from 172.20.0.1, the gateway of the Compose network: Docker's port publishing sits between the host and the server. Behind NAT or a load balancer, clientIp() gives that hop's address, not your machine's.

Four methods on eight connections

whoami.php connects to each server, prints the account and the system flag right after connect() and again after flush(), then the id and the address:

php
<?php
// whoami.php: what each server tells the client about its connection.
// php whoami.php <label>=<nats url> ...
declare(strict_types=1);

require __DIR__ . '/lib.php';

printf("%-12s %-8s %-13s %-13s %3s  %s\n", 'server', 'release',
    'connect()', 'flush()', 'cid', 'client ip');
foreach (array_slice($argv, 1) as $arg) {
    [$label, $url] = explode('=', $arg, 2);
    $c = client($url);
    $c->connect()->await();
    $afterConnect = seen($c);
    $c->flush()->await();
    printf("%-12s %-8s %-13s %-13s %3d  %s\n", $label, $c->serverInfo()->version,
        $afterConnect, seen($c), $c->clientId(), $c->clientIp());
    $c->disconnect()->await();
}
text
server       release  connect()     flush()       cid  client ip
s211         2.11.17  null    false null    false  12  172.20.0.1
s212         2.12.15  $G      false $G      false   8  172.20.0.1
s215         2.15.3   $G      false $G      false  18  172.20.0.1
acc211 a     2.11.17  null    false null    false  11  172.20.0.1
acc212 a     2.12.15  ORIGIN  false ORIGIN  false  10  172.20.0.1
acc a        2.15.3   ORIGIN  false ORIGIN  false  66  172.20.0.1
acc b        2.15.3   TARGET  false TARGET  false  67  172.20.0.1
acc sys      2.15.3   SYS     true  SYS     true   68  172.20.0.1
  • On 2.11.17 the account stays null and the flag false, also on acc211, which has the same accounts as acc. The server does not send the account, so there is nothing to read.
  • From 2.12.15 every connection knows its account: $G without accounts, and ORIGIN, TARGET or SYS according to the user. Only sys got true.
  • Here the account was known as soon as connect() returned. The server's answer came in the same read as the PONG, which is the usual case. The next section breaks that on purpose.
  • Each server numbers its own connections. s212 gave the id 8 while acc was already at 66: a client id identifies a connection on one server, not across servers.

A worker that checks where it landed

The simplest use is a start-up check. guard.php refuses to run in the system account, in an account it did not expect, or when the server does not say:

php
<?php
// guard.php: a worker that starts only in the account it expects.
// php guard.php <nats url> <expected account>
declare(strict_types=1);

require __DIR__ . '/lib.php';

[, $url, $expected] = $argv;
$c = client($url);
$c->connect()->await();
$c->flush()->await();     // the account may come in the read after the PONG's
$account = $c->remoteAccount();
$where = sprintf('%s as cid %d', $c->serverInfo()->serverName, $c->clientId());
if ($c->isSystemAccount()) {
    echo "refused: $where is in the system account ($account)\n";
    exit(1);
}
if ($account === null) {
    echo "refused: $where did not say its account (nats-server before 2.12)\n";
    exit(1);
}
if ($account !== $expected) {
    echo "refused: $where is in $account, not in $expected\n";
    exit(1);
}
echo "started: $where in $account\n";
$c->disconnect()->await();
text
started: acc as cid 69 in ORIGIN
exit 0
refused: acc as cid 70 is in the system account (SYS)
exit 1
refused: acc as cid 71 is in TARGET, not in ORIGIN
exit 1
refused: acc211 as cid 12 did not say its account (nats-server before 2.12)
exit 1

A worker with the wrong credentials now stops at start with a sentence instead of running silently in the wrong place. Whether an unknown account should stop it is your call: we fail closed, which would stop every worker on a server older than 2.12. A fleet that still runs such servers may prefer a warning there.

When the account comes late

connect() returns once the server has answered the first PING. It does not wait for the INFO that carries the account, which a server before 2.12 never sends. When that INFO comes in a later read than the PONG, the account is null until the client reads again. info-proxy.php makes that happen: in late mode it holds the INFO that follows the first PONG for 300 ms. Its forge mode is for the next section:

php
<?php
// info-proxy.php: a TCP proxy that changes how a server's INFO reaches the client.
// php info-proxy.php <listen port> <server host:port> late <ms> <lifetime s>
//   holds the INFO that follows the first PONG for <ms>, so it comes in a later read
// php info-proxy.php <listen port> <server host:port> forge 0 <lifetime s>
//   adds "remote_account":"SYS" and "acc_is_sys":true to the greeting INFO
declare(strict_types=1);

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

use Amp\Socket\BindContext;
use Amp\Socket\ConnectContext;
use Amp\Socket\Socket;

use function Amp\async;
use function Amp\delay;
use function Amp\Socket\connect;
use function Amp\Socket\listen;

[, $port, $target, $mode, $ms, $seconds] = $argv;

function forge(string $greeting): string
{
    $info = json_decode(substr($greeting, 5), true);
    $info['remote_account'] = 'SYS';
    $info['acc_is_sys'] = true;
    return 'INFO ' . json_encode($info, JSON_UNESCAPED_SLASHES) . "\r\n";
}

function relay(Socket $client, Socket $server, string $mode, float $hold): void
{
    async(function () use ($client, $server): void {
        try {
            while (($bytes = $client->read()) !== null) {
                $server->write($bytes);
            }
            $server->end();
        } catch (\Throwable) {
            $server->close();
        }
    });
    $buffer = '';
    $done = false;     // the change is made once per connection
    try {
        while (($bytes = $server->read()) !== null) {
            if (!$done && $mode === 'forge') {
                $buffer .= $bytes;           // the greeting, up to its end of line
                if (($end = strpos($buffer, "\r\n")) === false) {
                    continue;
                }
                $bytes = forge(substr($buffer, 0, $end)) . substr($buffer, $end + 2);
                $done = true;
            }
            $at = $done ? false : strpos($bytes, "PONG\r\n");
            if ($mode === 'late' && $at !== false) {
                $client->write(substr($bytes, 0, $at + 6));
                $bytes = substr($bytes, $at + 6);
                if ($bytes === '') {
                    $bytes = $server->read() ?? '';   // the INFO, when it comes apart
                }
                delay($hold);
                $done = true;
            }
            $client->write($bytes);
        }
        $client->end();
    } catch (\Throwable) {
        $client->close();
    }
}

$listener = listen("127.0.0.1:$port", (new BindContext())->withTcpNoDelay());
async(function () use ($listener, $target, $mode, $ms): void {
    while ($client = $listener->accept()) {
        $server = connect($target, (new ConnectContext())->withTcpNoDelay());
        async(fn() => relay($client, $server, $mode, (int) $ms / 1000));
    }
});
printf("127.0.0.1:%s -> %s, %s %s ms, for %s s\n", $port, $target, $mode, $ms, $seconds);
delay((float) $seconds);
exit(0);

late.php prints the account after connect(), after a publish(), which writes but does not read, and after flush():

php
<?php
// late.php: when is the account known? Right after connect(), after a publish(),
// after flush(). php late.php <nats url>
declare(strict_types=1);

require __DIR__ . '/lib.php';

$c = client($argv[1]);
$t0 = hrtime(true) / 1e9;
$c->connect()->await();
echo since($t0), '  connect() returned      ', seen($c), PHP_EOL;
$c->publish('demo', 'hello')->await();
echo since($t0), '  publish() returned      ', seen($c), PHP_EOL;
$c->flush()->await();
echo since($t0), '  flush() returned        ', seen($c), PHP_EOL;
printf("%s  cid %d, client ip %s, server %s\n", since($t0), $c->clientId(),
    $c->clientIp(), $c->serverInfo()->serverName);
$c->disconnect()->await();

Straight to the 2.15.3 server:

text
 0.004 s  connect() returned      $G      false
 0.004 s  publish() returned      $G      false
 0.004 s  flush() returned        $G      false
 0.004 s  cid 19, client ip 172.20.0.1, server s215

Through the proxy:

text
 0.004 s  connect() returned      null    false
 0.004 s  publish() returned      null    false
 0.306 s  flush() returned        $G      false
 0.306 s  cid 20, client ip 172.20.0.1, server s215

Through the proxy the account was still null after connect() and after publish(), and it was $G once flush() returned, 0.306 s in. flush() sends a PING and reads until its PONG, so it reads the held INFO on the way. That is the advice of the release notes, and the changelog notes that nats.go gives the same for its RemoteAccount(): call flush() after connect() when you need the account at once, as guard.php does.

A greeting that lies

The client reads the greeting before it sends CONNECT, and before a TLS upgrade the greeting travels in plaintext. Anyone on the path can add fields to it. 2.43.0 therefore takes the account only from the INFO that answers CONNECT, and an account in the greeting is ignored. The forge proxies add "remote_account":"SYS" and "acc_is_sys":true to every greeting:

text
  <- INFO server_name="acc" version="2.15.3" client_id=72 client_ip="172.20.0.1"
          remote_account="SYS" acc_is_sys=true
  -> CONNECT, PING
  <- PONG
  <- INFO server_name="acc" version="2.15.3" client_id=72 client_ip="172.20.0.1"
          connect_info=true remote_account="ORIGIN"
text
server       release  connect()     flush()       cid  client ip
s211         2.11.17  null    false null    false  13  172.20.0.1
acc a        2.15.3   ORIGIN  false ORIGIN  false  73  172.20.0.1

The client believed neither. On 2.11.17, which sends no answer of its own, the account stayed null and the flag false. On 2.15.3 the real answer named ORIGIN, and that is what the client reports. A forged greeting cannot make a connection look like it is in the system account.

Find your connection in the monitoring

clientId() is the key to the server's own view of your connection. connz.php opens three workers with the same user and looks each one up in the monitoring endpoint by its id:

php
<?php
// connz.php: three workers find their own connections in the server's monitoring.
// php connz.php <nats url> <monitoring url>
declare(strict_types=1);

require __DIR__ . '/lib.php';

[, $url, $monitor] = $argv;
$workers = [];
foreach (['worker-1', 'worker-2', 'worker-3'] as $name) {
    $workers[$name] = client($url, name: $name);
    $workers[$name]->connect()->await();
    $workers[$name]->flush()->await();
}
$all = json_decode(file_get_contents("$monitor/connz"), true);
echo "connections on the server: {$all['num_connections']}\n";
foreach ($workers as $name => $c) {
    $id = $c->clientId();
    $connz = json_decode(file_get_contents("$monitor/connz?cid=$id&auth=true"), true);
    $conn = $connz['connections'][0];
    printf("%s: clientId() %d, account %s\n", $name, $id, $c->remoteAccount());
    printf("  connz?cid=%d: name %s, account %s, user %s, from %s:%d\n", $id,
        $conn['name'], $conn['account'], $conn['authorized_user'], $conn['ip'],
        $conn['port']);
}
foreach ($workers as $c) {
    $c->disconnect()->await();
}
text
connections on the server: 3
worker-1: clientId() 74, account ORIGIN
  connz?cid=74: name worker-1, account ORIGIN, user app, from 172.20.0.1:46562
worker-2: clientId() 75, account ORIGIN
  connz?cid=75: name worker-2, account ORIGIN, user app, from 172.20.0.1:46566
worker-3: clientId() 76, account ORIGIN
  connz?cid=76: name worker-3, account ORIGIN, user app, from 172.20.0.1:46570

The three workers share a user, an account and an address, and they could share a name too, as replicas often do. Only the id tells them apart. Here is the server's full record for one more worker-1 connection that we kept open for 45 seconds, as the monitoring endpoint shows it in a browser; the client also reports its language and its release:

nats-server 2.15.3 monitoring at /connz?cid=85&auth=true for the connection whose clientId() returned 85: name worker-1, lang php, version v2.43.0, user app, account ORIGIN

A reconnect into another account

A new connection starts over: its account is null until its own answer arrives, so a reconnect that lands in another account shows. To get one, reconnect.php puts a proxy in front of two servers. The first dial goes to acc, where app is in ORIGIN, and every later one to moved, where app is in TARGET. A second connection, in acc's system account, then kicks the worker off acc by its client id, with the system request $SYS.REQ.SERVER.<server id>.KICK:

php
<?php
// reconnect.php: a reconnect that lands in another account.
// php reconnect.php <server A host:port> <server B host:port> <system user url of A>
// A proxy in front of the two servers sends the first dial to A and every later
// one to B. The user "app" is in ORIGIN on A and in TARGET on B. A connection in
// A's system account kicks the app's connection off A by its client id.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use Amp\DeferredFuture;
use Amp\TimeoutCancellation;
use IDCT\NATS\Connection\Enum\ConnectionEvent;

use function Amp\async;
use function Amp\ByteStream\pipe;
use function Amp\Socket\connect;
use function Amp\Socket\listen;

[, $serverA, $serverB, $sysUrl] = $argv;

$proxy = listen('127.0.0.1:0');
$dials = 0;
async(function () use ($proxy, $serverA, $serverB, &$dials): void {
    while ($down = $proxy->accept()) {
        $up = connect(++$dials === 1 ? $serverA : $serverB);
        async(function () use ($down, $up): void {
            try { pipe($down, $up); } finally { $up->close(); }
        })->ignore();
        async(function () use ($down, $up): void {
            try { pipe($up, $down); } finally { $down->close(); }
        })->ignore();
    }
})->ignore();

$back = new DeferredFuture();
$app = null;
$app = client('nats://app:app@' . $proxy->getAddress(),
    connectionListener: function (ConnectionEvent $e) use (&$app, $back): void {
        printf("  event %-12s account %s cid %s\n", $e->name, seen($app),
            $app->clientId() ?? 'null');
        if ($e === ConnectionEvent::Reconnected && !$back->isComplete()) {
            $back->complete();
        }
    });
$app->connect()->await();
$app->flush()->await();
printf("on %-6s account %s cid %d\n", $app->serverInfo()->serverName, seen($app),
    $app->clientId());

$sys = client($sysUrl);
$sys->connect()->await();
$cid = $app->clientId();
$kick = '$SYS.REQ.SERVER.' . $app->serverInfo()->serverId . '.KICK';
$reply = $sys->request($kick, json_encode(['cid' => $cid]), 2000)->await();
$answer = json_decode($reply->payload, true);
printf("KICK cid %d: answered by %s, error %s\n", $cid, $answer['server']['name'],
    json_encode($answer['error'] ?? null));

try {
    $app->flush()->await();   // the next read finds the connection gone
} catch (\Throwable $e) {
    echo 'flush(): ', $e->getMessage(), PHP_EOL;
}
$back->getFuture()->await(new TimeoutCancellation(5));
$app->flush()->await();
printf("on %-6s account %s cid %d, dials %d\n", $app->serverInfo()->serverName,
    seen($app), $app->clientId(), $dials);

$sys->disconnect()->await();
$app->disconnect()->await();
$proxy->close();
text
  event Connected    account ORIGIN  false cid 77
on acc    account ORIGIN  false cid 77
KICK cid 77: answered by acc, error null
  event Disconnected account ORIGIN  false cid 77
  event Reconnected  account TARGET  false cid 12
flush(): Connection lost before the server answered the PING
on moved  account TARGET  false cid 12, dials 2
  event Closed       account TARGET  false cid 12
  • The kick worked by id. The server answered without an error and closed exactly that connection.
  • While the connection was down, the methods still described it: at the Disconnected event they gave ORIGIN and cid 77.
  • The new connection reported its own values. At the Reconnected event the account was already TARGET with cid 12 on moved: its answer had come with the PONG. A listener on Reconnected that compares the account with the one before can catch a worker that moved without anyone noticing.
  • The flush() that was in flight on the kicked connection failed with "Connection lost before the server answered the PING". The reconnect went ahead anyway, and the next flush() ran on the new connection.

Later INFOs on the same connection, such as a cluster topology change or lame duck mode, carry no account, and the client keeps the one it has while the id and the address follow each INFO. We did not run those two here; the changelog lists unit tests for both.

2.42.1: one lookup per refused publish

2.42.1 is an internal patch release. When the server refuses a publish with a "Permissions Violation for Publish" -ERR, the error names only the subject. The client used to scan every request in flight and every watched pull to find the ones on that subject; it now finds them with one lookup in a map by subject. Each request in flight and each watched pull is now one internal record. The release notes say no one has to upgrade for it: nothing changes in the public API or on the wire.

refused.php checks the behaviour that must not change. The user lim may not publish to secret.>. Four requests go out at once: two to a subject a responder answers after 300 ms, and two to the same refused subject:

php
<?php
// refused.php: a refused request fails at once, and only requests to its subject do.
// php refused.php <nats url of "lim">
// "lim" may not publish to secret.>. A responder on another connection answers
// requests to slow.> after 300 ms.
declare(strict_types=1);

require __DIR__ . '/lib.php';

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

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

$responder = client($argv[1]);
$responder->connect()->await();
$responder->subscribe('slow.>', function (NatsMessage $m) use ($responder): void {
    async(function () use ($m, $responder): void {
        delay(0.3);
        $responder->publish($m->replyTo, "reply to $m->subject")->await();
    });
})->await();
$stop = false;
$reading = async(function () use ($responder, &$stop): void {
    while (!$stop) {
        try {
            $responder->processIncoming(new TimeoutCancellation(0.1))->await();
        } catch (CancelledException) {
        }
    }
});

$c = client($argv[1]);
$c->connect()->await();
$t0 = hrtime(true) / 1e9;
$calls = [];
foreach (['slow.1', 'secret.1', 'secret.1', 'slow.2'] as $n => $subject) {
    $calls[] = async(function () use ($c, $n, $subject, $t0): void {
        try {
            $reply = $c->request($subject, 'x', 2000)->await();
            echo since($t0), "  #$n $subject: ", $reply->payload, PHP_EOL;
        } catch (\Throwable $e) {
            $class = (new \ReflectionClass($e))->getShortName();
            echo since($t0), "  #$n $subject: $class\n    ",
                wordwrap($e->getMessage(), 80, "\n    "), PHP_EOL;
        }
    });
}
foreach ($calls as $call) {
    $call->await();
}
$stop = true;
$reading->await();
$c->disconnect()->await();
$responder->disconnect()->await();
text
 0.001 s  #1 secret.1: PermissionViolationException
    The server refused the request to "secret.1": Permissions Violation for Publish
    to "secret.1". No responder received it. Grant this connection's user permission
    to publish to "secret.1".
 0.001 s  #2 secret.1: PermissionViolationException
    The server refused the request to "secret.1": Permissions Violation for Publish
    to "secret.1". No responder received it. Grant this connection's user permission
    to publish to "secret.1".
 0.302 s  #0 slow.1: reply to slow.1
 0.303 s  #3 slow.2: reply to slow.2

Both refused requests failed at once, each with its own -ERR, and the two others got their replies 300 ms later. We ran the same script in a 2.42.0 install and a 2.42.1 install, and compared the outputs with the timings cut off:

bash
#!/bin/bash
# same.sh: refused.php's output in 2.42.0 and 2.42.1 against 2.43.0, timings cut off.
cd "$(dirname "$0")/output"
for v in 2.42.0 2.42.1; do
  diff <(cut -c10- refused-$v.txt) <(cut -c10- refused-2.43.0.txt) && echo "$v: same"
done
text
2.42.0: same
2.42.1: same

We did not time the lookup itself. The rest of 2.42.1 is tests and documentation: the second integration stage now runs against nats-server 2.14 with the js_ack_fc_v2 flag, so the whole live suite covers the v2 JetStream ack subjects that servers send by default from 2.16; a new fixture runs the README's "Account imports" configuration with 15 live tests through jetStream(apiPrefix:); and a new README section, "JetStream Message Metadata", documents messageMetadata(), streamSequenceOf() and the fields of JsMessageMetadata.

Quality gates

From the 2.43.0 release notes: PHPStan level 8, with the PHPStan 2.4.0 that CI installs reporting no errors; 4666 unit tests on PHP 8.2 to 8.5, 25 more than in 2.42.1, all in the new ServerInfoAccountTest; 228 live integration tests against the nats-server 2.12 fixture stack, 26 of them skipped there because they need 2.14 or its v2 ack form, and 224 passing in a second run against 2.14 with js_ack_fc_v2, where nothing may skip. The new ConnectionAccountIntegrationTest checks $G on the main server and two named accounts on the accounts fixture. All 54 Behat scenarios and all 47 runnable examples pass, every changed line is covered and total coverage is 99.16%. In the review, 24 wrong versions of the new code were tried one at a time, among them an account taken from the greeting and an account dropped by a later INFO, and each turned at least one test red.

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.