php-nats-jetstream-client 2.34: leaf nodes and account imports
(php, nats, release-notes) 22 min read by Bartosz Pachołek
2.34.0 adds jetStream(domain:) and jetStream(apiPrefix:): a PHP service on a leaf node can use the hub's JetStream, and an account can use another account's through an import. We ran both, plus what the README does not list yet.
idct/php-nats-jetstream-client 2.34.0 is out, and it lets a PHP service use a JetStream that is not its own: the JetStream of a hub, reached through a leaf node under a JetStream domain, or the JetStream of another account, reached through an import under an API prefix. Both are one argument: $client->jetStream(domain: 'hub') and $client->jetStream(apiPrefix: 'JS.from-a.API'). Until now every JetStream, KeyValue and Object Store call went to the fixed $JS.API. subjects, and a leaf node without JetStream of its own answers those with "no responders".
Our last post on the client covered 2.33.0, and 2.34.0 is the only release since. We ran every example below on PHP 8.5.9 against nats-server 2.14.10 and 2.12.15 in Docker, with 2.34.0 from Packagist and, for the before-and-after comparison, 2.33.0. The output is pasted as it came out. We also ran two things the release says it did not run live: resetConsumer() through a leaf node, and an account import, which needs more configuration than the README lists so far.
Upgrading
composer require idct/php-nats-jetstream-client:^2.34
Existing calls need no change: jetStream() without arguments returns the same context as before, and it still sends to $JS.API.. Before you use the new arguments, check these:
- The server version checks read the server the client is connected to. Through a leaf node that is the leaf node's version, not the hub's. Through a 2.12 leaf node
resetConsumer()is refused before anything is sent, although a 2.14 hub would answer it. The same holds for the version-gated stream and consumer fields,batch()andpublishScheduled(). We show it below. - A domain together with a prefix is refused with a
JetStreamException. That is this client's own rule: nats.go's legacy options and nats.java let the last one set win. - An account import needs more than the README lists so far. The release notes say so themselves and issue #281 tracks it. We ran both configurations; the section on account imports has the details.
- The
domainshorthand of a KV mirror or source, andStreamSource::external(), are unchanged. They name where the origin stream lives and do not depend on the context's prefix.
The full record is in the changelog at v2.34.0.
Why a leaf node could not reach JetStream
A leaf node is a NATS server that extends a hub to another place: a site, a store, a vehicle. Local clients connect to the leaf node, and their messages reach the hub, and the hub's reach them, wherever there is interest on the other side. JetStream often runs only on the hub. To keep the JetStream of the hub apart from any JetStream a leaf node might run, the hub's is given a domain (jetstream { domain: hub }), and its API answers under that domain as $JS.hub.API.>. The plain $JS.API.> on the leaf node means the leaf node's own JetStream. When it has none, nothing answers.
An account import is the same problem with a different cause. Accounts in NATS are isolated from each other. An account that runs JetStream can export its API as a service, and another account imports it under a subject of its own choosing, for example JS.from-a.API.>. A client in the importing account has to send its JetStream requests there, not to $JS.API.>.
nats.go offers both, as jetstream.NewWithDomain() and jetstream.NewWithAPIPrefix(), and nats.java as JetStreamOptions.domain() and prefix(). The PHP client had neither: the issue behind this release lists where $JS.API. was fixed in the code.

In 2.34.0 a context takes a domain or a prefix, and every JetStream API request it makes uses it: streams, consumers, account info, message get and delete, Direct Get, pulls (fetchBatch() and pullConsumer()->handle()), pause, unpin, resetConsumer(), and the requests of the KeyValue and Object Store buckets taken from the context. What is not an API request keeps its own subject: a JetStream publish goes to the stream's subject, the Object Store's chunk and meta publishes to theirs, and acks and flow-control replies to the reply subject the server gave.
A proof of concept you can run
A hub with JetStream under the domain hub, a leaf node on 2.14 and one on 2.12 without JetStream, two servers with accounts for the import, four scripts, and the client from Packagist:
services:
hub:
image: nats:2.14-alpine
command: ["-c", "/etc/nats/hub.conf"]
volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
ports: ["14434:4222"]
leaf:
image: nats:2.14-alpine
command: ["-c", "/etc/nats/leaf.conf"]
volumes: ["./leaf.conf:/etc/nats/leaf.conf:ro"]
ports: ["14435:4222"]
depends_on: [hub]
leaf-2-12:
image: nats:2.12-alpine
command: ["-c", "/etc/nats/leaf-2-12.conf"]
volumes: ["./leaf-2-12.conf:/etc/nats/leaf-2-12.conf:ro"]
ports: ["14436:4222"]
depends_on: [hub]
import-readme:
image: nats:2.14-alpine
command: ["-c", "/etc/nats/import-readme.conf"]
volumes: ["./import-readme.conf:/etc/nats/import-readme.conf:ro"]
ports: ["14438:4222"]
import-full:
image: nats:2.14-alpine
command: ["-c", "/etc/nats/import-full.conf"]
volumes: ["./import-full.conf:/etc/nats/import-full.conf:ro"]
ports: ["14439:4222"]
The hub and the leaf node follow the fixtures the release added to the repository:
# hub.conf: JetStream under the domain "hub", and a port for leaf nodes.
port: 4222
server_name: hub
jetstream {
domain: hub
}
leafnodes {
port: 7422
}
# leaf.conf: no JetStream of its own, connected to the hub.
port: 4222
server_name: leaf
leafnodes {
remotes: [
{ url: "nats-leaf://hub:7422" }
]
}
leaf-2-12.conf is the same file with server_name: leaf-2-12. The import configurations come later, in their own section.
{
"require": {
"php": "^8.2",
"idct/php-nats-jetstream-client": "^2.34"
}
}
The commands for all four scripts:
docker compose up -d
composer install
php leaf.php # leaf node 14435, hub 14434
php rules.php
php versions.php nats://127.0.0.1:14435 # leaf node on nats-server 2.14
php versions.php nats://127.0.0.1:14436 # leaf node on nats-server 2.12
php import.php nats://127.0.0.1:14438 # the imports the README lists
php import.php nats://127.0.0.1:14439 # plus what the NATS docs ask for
leaf.php connects to the leaf node and does what a service does with JetStream: it creates a stream and a durable consumer, publishes, pulls and acks, writes and reads a KeyValue bucket and stores a 300 KiB object. At the end a second client, connected to the hub itself, reads the same data back with the default context.
<?php
// leaf.php: use the hub's JetStream from a client connected to a leaf node.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\Exception\NatsException;
$leaf = $argv[1] ?? 'nats://127.0.0.1:14435';
$hub = $argv[2] ?? 'nats://127.0.0.1:14434';
$client = new NatsClient(new NatsOptions(servers: [$leaf]));
$client->connect()->await();
$info = $client->serverInfo();
printf("Connected to %s, nats-server %s\n", $info?->serverName, $info?->version);
echo "1. The default context:\n";
try {
$client->jetStream()->accountInfo()->await();
echo " JetStream answered\n";
} catch (JetStreamException $e) {
echo ' ', $e->getCode(), ' ', wordwrap($e->getMessage(), 80, "\n "), PHP_EOL;
}
echo "2. A context for the domain hub:\n";
try {
$js = $client->jetStream(domain: 'hub');
} catch (\Error $e) {
echo ' ', $e::class, ': ', $e->getMessage(), PHP_EOL;
exit(1);
}
echo ' API prefix ', $js->apiPrefix(), PHP_EOL;
$account = $js->accountInfo()->await();
echo ' account info answered by domain ', $account->raw['domain'] ?? '?', PHP_EOL;
echo "3. A stream, a consumer, a publish, a pull and an ack:\n";
try {
$js->deleteStream('ORDERS')->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
$js->createStream('ORDERS', ['orders.>'])->await();
$js->createConsumer('ORDERS', 'worker', null, ['ack_policy' => 'explicit'])->await();
$ack = $js->publish('orders.created', '{"id":1}')->await();
$domain = $ack->raw['domain'] ?? '-';
printf(" published: stream %s, seq %d, domain %s\n", $ack->stream, $ack->seq, $domain);
foreach ($js->fetchBatch('ORDERS', 'worker', 10, 1000)->await() as $message) {
echo ' fetched ', $message->payload, ' from ', $message->subject, PHP_EOL;
$js->ackSync($message)->await();
}
$consumer = $js->getConsumer('ORDERS', 'worker')->await();
printf(
" consumer: %d pending, %d awaiting ack\n",
$consumer->raw['num_pending'] ?? -1,
$consumer->raw['num_ack_pending'] ?? -1,
);
echo "4. A KeyValue bucket and an Object Store bucket:\n";
$kv = $js->keyValue('config');
try {
$kv->deleteBucket()->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
$kv->create()->await();
$revision = $kv->put('theme', 'dark')->await()->seq;
$entry = $kv->get('theme')->await();
printf(" put theme=dark (revision %d), read back %s\n", $revision, $entry?->value);
try {
// The subject a KV put used before 2.34.0, sent by hand.
$client->request('$KV.config.theme', 'light', 2000)->await();
echo " plain \$KV.config.theme: answered\n";
} catch (NatsException $e) {
$class = substr(strrchr($e::class, '\\'), 1);
echo ' plain $KV.config.theme: ', $class, ': ', $e->getMessage(), PHP_EOL;
}
$files = $js->objectStore('files');
try {
$files->deleteBucket()->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
$files->create()->await();
$report = random_bytes(300 * 1024);
$put = $files->put('report.bin', $report)->await();
$back = $files->get('report.bin')->await();
printf(
" put report.bin: %d bytes in %d chunks, read back %s\n",
$put->size,
$put->chunks,
$back->data === $report ? 'identical' : 'DIFFERENT',
);
$client->disconnect()->await();
echo "5. The same data, read by a client connected to the hub:\n";
$direct = new NatsClient(new NatsOptions(servers: [$hub]));
$direct->connect()->await();
$name = $direct->serverInfo()?->serverName;
$hubJs = $direct->jetStream();
$state = $hubJs->getStream('ORDERS')->await()->raw['state'] ?? [];
printf(" %s: stream ORDERS with %d message(s)\n", $name, $state['messages'] ?? -1);
$theme = $hubJs->keyValue('config')->get('theme')->await()?->value;
printf(" %s: config.theme = %s\n", $name, $theme);
$direct->disconnect()->await();
With 2.34.0:
Connected to leaf, nats-server 2.14.10
1. The default context:
503 No JetStream responder for subject $JS.API.INFO (the subject is not bound to a
stream, or JetStream is not enabled)
2. A context for the domain hub:
API prefix $JS.hub.API.
account info answered by domain hub
3. A stream, a consumer, a publish, a pull and an ack:
published: stream ORDERS, seq 1, domain hub
fetched {"id":1} from orders.created
consumer: 0 pending, 0 awaiting ack
4. A KeyValue bucket and an Object Store bucket:
put theme=dark (revision 1), read back dark
plain $KV.config.theme: NatsException: No responders for subject $KV.config.theme
put report.bin: 307200 bytes in 3 chunks, read back identical
5. The same data, read by a client connected to the hub:
hub: stream ORDERS with 1 message(s)
hub: config.theme = dark
What the run shows:
- The leaf node has no JetStream of its own. The default context gets a 503 on
$JS.API.INFO, as it did before the release. - The domain context reaches the hub. Its prefix is
$JS.hub.API., and the account info that comes back names the domainhub. - The publish is not prefixed. The message goes to
orders.created, the hub's streamORDERSstores it, and the publish ack names the domain it was stored in. The pull goes through the prefix, the ack goes to the reply subject the server gave, and the consumer has nothing left pending. - KeyValue writes go through the prefix. The client sends a put to
$JS.hub.API.$KV.config.theme, as nats.go does, and nats-server maps it back to$KV.config.themeon the hub, so the stored subject and every read stay the same. The line after the put shows why: a request sent by hand to the plain$KV.config.theme, the subject a put used before, gets "no responders" on the leaf node. - The Object Store works too. The 300 KiB object went out as three chunks on the bucket's own subjects and came back byte for byte.
- It all lives on the hub. The client connected to the hub sees the stream with its message and the key with its value.
With 2.33.0 the same script stops at the second step, because there was no way to name a domain:
Connected to leaf, nats-server 2.14.10
1. The default context:
503 No JetStream responder for subject $JS.API.INFO (the subject is not bound to a
stream, or JetStream is not enabled)
2. A context for the domain hub:
Error: Unknown named parameter $domain

What a context accepts
A domain is a single subject token, and a prefix is a subject. rules.php asks for a context with good and bad values and prints the subject each context would send a stream info request to. The client is never connected:
<?php
// rules.php: the domains and prefixes a context accepts, and which contexts are shared.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
// Never connected: everything below is decided before anything is sent.
$client = new NatsClient(new NatsOptions(servers: ['nats://127.0.0.1:14435']));
$calls = [
"jetStream()" => fn () => $client->jetStream(),
"jetStream(domain: 'hub')" => fn () => $client->jetStream(domain: 'hub'),
"jetStream(apiPrefix: 'JS.from-a.API')" => fn () => $client->jetStream(
apiPrefix: 'JS.from-a.API',
),
"jetStream(domain: '')" => fn () => $client->jetStream(domain: ''),
"jetStream(domain: 'eu.hub')" => fn () => $client->jetStream(domain: 'eu.hub'),
"jetStream(domain: 'hub*')" => fn () => $client->jetStream(domain: 'hub*'),
"jetStream(apiPrefix: 'JS..API')" => fn () => $client->jetStream(
apiPrefix: 'JS..API',
),
"jetStream(apiPrefix: 'JS.*.API')" => fn () => $client->jetStream(
apiPrefix: 'JS.*.API',
),
"jetStream(domain: 'hub', apiPrefix: 'JS.A')" => fn () => $client->jetStream(
domain: 'hub',
apiPrefix: 'JS.A',
),
];
foreach ($calls as $call => $make) {
echo $call, PHP_EOL;
try {
// The subject this context sends a stream info request for ORDERS to.
$subject = $make()->apiSubject('$JS.API.STREAM.INFO.ORDERS');
echo ' -> ', $subject, PHP_EOL;
} catch (JetStreamException $e) {
echo ' refused: ', wordwrap($e->getMessage(), 76, "\n "), PHP_EOL;
}
}
$same = fn (object $a, object $b): string => $a === $b ? 'one context' : 'two contexts';
echo PHP_EOL, 'jetStream() twice: ', $same(
$client->jetStream(),
$client->jetStream(),
), PHP_EOL;
echo "domain 'hub' and apiPrefix '\$JS.hub.API': ", $same(
$client->jetStream(domain: 'hub'),
$client->jetStream(apiPrefix: '$JS.hub.API'),
), PHP_EOL;
echo "jetStream() and domain 'hub': ", $same(
$client->jetStream(),
$client->jetStream(domain: 'hub'),
), PHP_EOL;
jetStream()
-> $JS.API.STREAM.INFO.ORDERS
jetStream(domain: 'hub')
-> $JS.hub.API.STREAM.INFO.ORDERS
jetStream(apiPrefix: 'JS.from-a.API')
-> JS.from-a.API.STREAM.INFO.ORDERS
jetStream(domain: '')
refused: JetStream domain must not be empty
jetStream(domain: 'eu.hub')
refused: Invalid JetStream domain "eu.hub": must not contain whitespace, control
characters, ".", "*" or ">"
jetStream(domain: 'hub*')
refused: Invalid JetStream domain "hub*": must not contain whitespace, control
characters, ".", "*" or ">"
jetStream(apiPrefix: 'JS..API')
refused: Invalid JetStream API prefix "JS..API": must be a subject of non-empty
tokens without whitespace, control characters, "*" or ">"
jetStream(apiPrefix: 'JS.*.API')
refused: Invalid JetStream API prefix "JS.*.API": must be a subject of non-empty
tokens without whitespace, control characters, "*" or ">"
jetStream(domain: 'hub', apiPrefix: 'JS.A')
refused: Set either a JetStream domain or a JetStream API prefix, not both
jetStream() twice: one context
domain 'hub' and apiPrefix '$JS.hub.API': one context
jetStream() and domain 'hub': two contexts
- A domain becomes
$JS.<domain>.API., and a prefix is used as given, with the trailing.added when it is missing. - Bad values are refused with a
JetStreamExceptionbefore anything is sent: an empty domain, one with.,*,>or whitespace, a prefix with an empty token or a wildcard, and a domain together with a prefix. Since none of this needs a connection, a typo fails where the context is made, not as "no responders" on the first request. - One context per prefix.
jetStream()returns the same context every time, as before. A domain and the prefix it stands for share one, and the default context is a different object from the domain's.new JetStreamContext($client, domain: 'hub')works too.
Version checks read the leaf node, not the hub
The client checks some calls against the server version before sending them. resetConsumer() from 2.33.0 is one of them: it needs nats-server 2.14, and older servers do not answer it. The version the client knows is the one in the INFO of the server it is connected to. Through a leaf node, that is the leaf node.
versions.php creates a stream and a consumer on the hub, a 2.14.10 server, through a leaf node, and resets the consumer:
<?php
// versions.php: the version checks read the server the client is connected to.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
$url = $argv[1] ?? 'nats://127.0.0.1:14435';
$client = new NatsClient(new NatsOptions(servers: [$url]));
$client->connect()->await();
$info = $client->serverInfo();
printf("Connected to %s, nats-server %s\n", $info?->serverName, $info?->version);
// The stream and the consumer live on the hub, nats-server 2.14.10.
$js = $client->jetStream(domain: 'hub');
try {
$js->deleteStream('AUDIT')->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
$js->createStream('AUDIT', ['audit.>'])->await();
$js->createConsumer('AUDIT', 'reader', null, ['ack_policy' => 'explicit'])->await();
$js->publish('audit.login', 'alice')->await();
echo " stream AUDIT and consumer reader created on the hub\n";
try {
$reset = $js->resetConsumer('AUDIT', 'reader', 1)->await();
echo ' resetConsumer(): done, next delivery from s', $reset->resetSequence, PHP_EOL;
} catch (JetStreamException $e) {
$class = substr(strrchr($e::class, '\\'), 1);
echo ' resetConsumer(): ', $class, PHP_EOL;
echo ' ', wordwrap($e->getMessage(), 80, "\n "), PHP_EOL;
}
$client->disconnect()->await();
Through the leaf node on 2.14.10:
Connected to leaf, nats-server 2.14.10
stream AUDIT and consumer reader created on the hub
resetConsumer(): done, next delivery from s1
Through the leaf node on 2.12.15, to the same hub:
Connected to leaf-2-12, nats-server 2.12.15
stream AUDIT and consumer reader created on the hub
resetConsumer(): UnsupportedFeatureException
Consumer reset requires NATS server 2.14+; older servers do not answer it
(connected server 2.12.15; nothing was sent)
The hub would have answered the reset both times. The client refuses it in the second run because the server it is connected to is 2.12.15, and it says which version it read and that nothing was sent. The release notes list this as a known limit, and it applies to every version check: the version-gated stream and consumer fields, batch() and publishScheduled() as well. If a service reaches JetStream through a leaf node and needs those calls, the leaf node has to run a version that has them, not only the hub. The release's own CI could not run this case, since its fixtures run 2.12; this run is the live version of it.
Account imports: what the README does not list yet
The README of 2.34.0 names three imports for an account that uses another account's JetStream: $JS.API.> under the prefix, $KV.> under the same prefix, and the subjects you publish to. The release notes add that the NATS documentation on cross-account subjects asks for three more things, that this part was not tested, and that issue #281 tracks the README change. We ran both.
This is the configuration with everything the release notes list:
# import-full.conf: plus what the NATS documentation asks for (issue #281).
port: 4222
server_name: import-full
jetstream {}
accounts {
A {
jetstream: enabled
users: [ { user: a, password: a } ]
exports: [
{ service: "$JS.API.>", response: stream }
{ service: "$KV.>" }
{ service: "orders.>" }
{ service: "$JS.ACK.>" }
{ stream: "_INBOX.JS.ORD.>" }
{ stream: "_INBOX.KV.KEYS.>" }
{ stream: "_INBOX.KV.HIST.>" }
{ stream: "_INBOX.JS.PUSH.>" }
]
}
B {
users: [ { user: b, password: b } ]
imports: [
{ service: { account: A, subject: "$JS.API.>" }, to: "JS.from-a.API.>" }
{ service: { account: A, subject: "$KV.>" }, to: "JS.from-a.API.$KV.>" }
{ service: { account: A, subject: "orders.>" } }
{ service: { account: A, subject: "$JS.ACK.>" } }
{ stream: { account: A, subject: "_INBOX.JS.ORD.>" } }
{ stream: { account: A, subject: "_INBOX.KV.KEYS.>" } }
{ stream: { account: A, subject: "_INBOX.KV.HIST.>" } }
{ stream: { account: A, subject: "_INBOX.JS.PUSH.>" } }
]
}
}
import-readme.conf is the same server with only the first three exports and imports, and with no response: stream on the API export. import.php runs as account B, which has no JetStream of its own, through the prefix JS.from-a.API, and then checks what account A sees:
<?php
// import.php: account B uses the JetStream of account A through its imports.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
$url = $argv[1] ?? 'nats://127.0.0.1:14439';
$options = fn (string $user) => new NatsOptions(
servers: [$url],
username: $user,
password: $user,
requestTimeoutMs: 3000,
);
// Runs one step and prints what it gave, or how it failed and after how long.
$step = function (string $label, \Closure $run): void {
$started = microtime(true);
try {
printf(" %-24s %s\n", $label, $run());
} catch (\Throwable $e) {
printf(" %-24s FAILED after %.1f s\n", $label, microtime(true) - $started);
$class = substr(strrchr($e::class, '\\'), 1);
echo ' ', wordwrap("$class: " . $e->getMessage(), 82, "\n "), PHP_EOL;
}
};
$b = new NatsClient($options('b'));
$b->connect()->await();
echo 'Server ', $b->serverInfo()?->serverName, ", account B:\n";
$step('default context', function () use ($b): string {
$b->jetStream()->accountInfo()->await();
return 'JetStream answered';
});
$js = $b->jetStream(apiPrefix: 'JS.from-a.API');
echo "Account B, context with the prefix JS.from-a.API:\n";
$step('account info', function () use ($js): string {
$js->accountInfo()->await();
return 'answered';
});
$step('stream and consumer', function () use ($js): string {
try {
$js->deleteStream('ORDERS')->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
$js->createStream('ORDERS', ['orders.>'])->await();
$js->createConsumer('ORDERS', 'worker', null, ['ack_policy' => 'explicit'])->await();
return 'created';
});
$step('publish 3 orders', function () use ($js): string {
$seqs = [];
foreach ([1, 2, 3] as $id) {
$seqs[] = $js->publish('orders.created', "{\"id\":$id}")->await()->seq;
}
return 'stored as ' . implode(', ', $seqs);
});
$messages = [];
$step('one pull of up to 10', function () use ($js, &$messages): string {
$messages = $js->fetchBatch('ORDERS', 'worker', 10, 1000)->await();
return count($messages) . ' message(s)';
});
$step('ackSync() each', function () use ($js, $messages): string {
foreach ($messages as $message) {
$js->ackSync($message)->await();
}
return count($messages) . ' confirmed';
});
$step('consumer state', function () use ($js): string {
$raw = $js->getConsumer('ORDERS', 'worker')->await()->raw;
$pending = $raw['num_pending'];
return sprintf('%d pending, %d awaiting ack', $pending, $raw['num_ack_pending']);
});
$kv = $js->keyValue('config');
$step('KV put and get', function () use ($kv): string {
try {
$kv->deleteBucket()->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
$kv->create(['history' => 5])->await();
$kv->put('theme', 'light')->await();
$kv->put('theme', 'dark')->await();
return 'theme = ' . $kv->get('theme')->await()?->value;
});
$step('KV keys()', fn (): string => implode(', ', $kv->keys(2.0)->await()));
$step('KV history()', function () use ($kv): string {
return count($kv->history('theme', 2.0)->await()) . ' revisions';
});
$b->disconnect()->await();
$a = new NatsClient($options('a'));
$a->connect()->await();
echo "Account A, its own user:\n";
$step('stream ORDERS', function () use ($a): string {
$info = $a->jetStream()->getConsumer('ORDERS', 'worker')->await()->raw;
return sprintf('ack floor at stream seq %d', $info['ack_floor']['stream_seq']);
});
$a->disconnect()->await();
With only what the README lists:
Server import-readme, account B:
default context FAILED after 0.0 s
JetStreamException: JetStream not enabled for account
Account B, context with the prefix JS.from-a.API:
account info answered
stream and consumer created
publish 3 orders stored as 1, 2, 3
one pull of up to 10 1 message(s)
ackSync() each FAILED after 0.0 s
NatsException: No responders for subject
$JS.ACK.ORDERS.worker.1.1.1.1795774176278968376.2
consumer state 0 pending, 3 awaiting ack
KV put and get theme = dark
KV keys() FAILED after 2.0 s
JetStreamException: Key enumeration stalled: no progress for 2.000 s (collected 0
key(s), replay not caught up)
KV history() FAILED after 2.0 s
JetStreamException: Key history for "theme" stalled: no progress for 2.000 s
(collected 0 revision(s), replay not caught up)
Account A, its own user:
stream ORDERS ack floor at stream seq 0
With the additions the NATS documentation asks for:
Server import-full, account B:
default context FAILED after 0.0 s
JetStreamException: JetStream not enabled for account
Account B, context with the prefix JS.from-a.API:
account info answered
stream and consumer created
publish 3 orders stored as 1, 2, 3
one pull of up to 10 3 message(s)
ackSync() each 3 confirmed
consumer state 0 pending, 0 awaiting ack
KV put and get theme = dark
KV keys() theme
KV history() 2 revisions
Account A, its own user:
stream ORDERS ack floor at stream seq 3
Each missing line shows up as its own failure:
- Without
response: streama pull gets one message. A service export allows one reply per request by default, and a pull answers with one message per reply. The consumer shows 3 awaiting ack: the server delivered all three, and account B received the first. - Without an import of
$JS.ACK.>acks have nowhere to go.ackSync()fails at once with "no responders", and account A's consumer keeps its ack floor at 0. Per the release notes, such messages are delivered again after the ack wait. We did not wait for that. - Without a stream export of the push delivery subjects,
keys()andhistory()stall. Both use a push consumer in account A that delivers to_INBOX.KV.KEYS.and_INBOX.KV.HIST.. Without the export the deliveries never reach account B, and the client gives up after the 2 seconds the script allows. Ordered consumers andwatch()deliver to_INBOX.JS.ORD., and push subscriptions without a delivery subject of their own to_INBOX.JS.PUSH.. Those are exported in the full configuration too, but we did not exercise them here.
With the additions, everything works: three messages in one pull, three confirmed acks, the key list and two revisions of history, and account A's consumer has its ack floor at 3.
Quality gates
From the release notes: PHPStan level 8; 4200 unit tests (with data sets) on PHP 8.2 to 8.5, 173 live integration tests and 51 Behat scenarios; all 47 runnable examples pass. Every changed line is covered (78 of 78), and total coverage is 99.11%. Infection reports a covered MSI of 92.73% against a 90% floor, with a caveat the release states itself: it skipped 5331 of the 9455 mutants it generated as too slow, so the score does not include them.
The new acceptance class JetStreamDomainTest has 178 cases over a scripted server that answers the JetStream API under one prefix only, as a leaf node of another domain does. 130 of them fail on 2.33.0. For the release, the fixed $JS.API. subject was put back at each of the 34 places that build an API subject, one at a time, and the new class failed for every one. The new live class JetStreamDomainIntegrationTest runs four cases through a real leaf node without JetStream, connected to a hub with the domain hub, on nats-server 2.12 in CI.
The release lists two paths as not run live: resetConsumer() through a leaf node, and the account import. Both are in this post, on the servers named above.
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.