php-nats-jetstream-client 2.41: settle a fast-ingest batch
(php, nats, release-notes) 22 min read by Bartosz Pachołek
2.41.0 adds FastPublisher::settle(): after an ack timeout it ends a fast-ingest batch and says how far the server got, so a cleanup no longer waits out the server's 10-second abandonment. We held a server's replies to show it. Plus four patch releases.
idct/php-nats-jetstream-client 2.41.0, our free NATS and JetStream client for PHP, adds one call to the fast-ingest batch publisher: FastPublisher::settle(). It ends a batch and returns the server's word on how the batch ended, and it works after the failure that used to leave you guessing, an ack timeout. Until now a publisher that timed out was closed, every later call failed without sending anything, and the batch stayed open on the server until the server gave up on it, 10 seconds later by default.
Our last post on the client covered 2.40.0. Four patch releases came out since: 2.40.1 fixes Object Store cleanups, 2.40.2 and 2.40.3 fix how the fast-ingest publisher handles a reconnect and a refused message, and 2.40.4 fixes requestMany(). We ran the examples below on PHP 8.5.9 with 2.40.0, 2.40.4 and 2.41.0 from Packagist, against nats-server 2.14.10 and 2.15.3 in Docker, with a small PHP proxy that holds a server's replies for a moment. The output is pasted as it came out.
The problem settle() solves
$js->fastPublisher(), new in 2.39.0, sends many messages into one stream as one fast-ingest batch (NATS ADR-50, nats-server 2.14 and later). The server does not acknowledge every message. It sends a flow ack every so many messages, and add() stops to wait only when too many acks are outstanding. A fast-ingest batch is not atomic: what the server receives is stored as it arrives, and a commit ends the batch.
That raises a question when something goes wrong halfway. Say the flow acks stop coming for a second, and add() gives up after its ack timeout. The client closes the publisher and releases its control inbox, but it does not know how far the server got, and the server still holds the batch open. Code that wants all or nothing, an upload that must not stay half-written for instance, has to purge what the batch stored. Before 2.41.0 it could purge at once and hope that nothing of the batch was still on its way, or wait out the server's idle abandonment first.
settle() closes that gap. It is the one call that works on a closed publisher, and it returns a new FastBatchEnd:
pubAckandfailure, the server's answer.failureis null when the batch ended with every message the publisher sent. Otherwise it is the exceptionadd()andcommit()throw for that end: a gap, a refused message, or a batch the server no longer knows (err_code 10208).nothingSent(): the publisher never sent a message, so there is no batch on the server.- An exception only when the server does not answer: a
TimeoutException, aConnectionException, the error of a read that failed, or a rejected control inbox.settle()may then be called again.
To get that answer after a timeout, settle() subscribes the batch's control inbox again, sends an EOB commit (a commit that carries no message) at the next batch sequence and waits up to the ack timeout for the reply that ends the batch. When it returns, the server has handled every message the publisher sent, and the publisher sends nothing more. One limit, which the release notes state plainly: it does not promise that the server's batch has ended. A check the server makes before a message reaches the batch, such as a sealed stream or a server or account limit, can answer the EOB commit with an error and leave the batch open until the server abandons it.

Upgrading
composer require idct/php-nats-jetstream-client:^2.41
Code that does not call settle() works as before, apart from one message. A call made while another call of the same publisher still runs is refused as before, but the refusal now reads "another add(), commit(), close() or settle() is still running". Update any code or log filter that matches the old wording.
If you skipped the 2.40 patch releases, three more changes deserve a look:
- 2.40.1: a
TimeoutExceptionorConnectionExceptionfrom an Object Storeput()orputStream()now means "the outcome is unknown", not "nothing was stored".info()tells you which revision the name holds, and retrying the upload still repairs it. - 2.40.2: a stalled fast-ingest
add()whose reconnect takes longer than the ack timeout now ends with aTimeoutExceptionand a closed publisher, and one whose client reconnects in time no longer throws. - 2.40.3: in gap mode
fail, a message the server refuses now ends the call with aFastBatchExceptioninstead of a bareJetStreamException.catch (JetStreamException)still catches it, but the server's err_code moved togetPrevious().
The full record is in the changelog at v2.41.0.
A proof of concept you can run
One Docker Compose project with four servers: nats-server 2.14.10 and 2.15.3 as they come, and the same two releases with a limit of one fast-ingest batch in flight per stream. That limit makes an open batch visible: while one batch is open, the server refuses the next one on the same stream with err_code 10211.
# The servers of the 2.41 examples: nats-server 2.14 and 2.15, and the same two
# releases with at most one fast-ingest batch in flight per stream (one.conf).
name: settle
services:
s214:
image: nats:2.14-alpine # 2.14.10
command: [-js, -n, s214]
ports: ["15114:4222"]
s215:
image: nats:2.15.3-alpine
command: [-js, -n, s215]
ports: ["15115:4222"]
one214:
image: nats:2.14-alpine # 2.14.10
command: [-c, /etc/nats/one.conf, -js, -n, one214]
volumes: ["./one.conf:/etc/nats/one.conf:ro"]
ports: ["15124:4222"]
one215:
image: nats:2.15.3-alpine
command: [-c, /etc/nats/one.conf, -js, -n, one215]
volumes: ["./one.conf:/etc/nats/one.conf:ro"]
ports: ["15125:4222"]
# At most one fast-ingest batch in flight per stream, so that a batch left open
# shows: the next one is refused with 10211. The idle timeout stays at 10 s.
jetstream {
limits {
batch {
max_inflight_per_stream: 1
}
}
}
{
"require": {
"php": "^8.2",
"idct/php-nats-jetstream-client": "^2.41"
}
}
Every script loads a few helpers. countOn() asks the server how many messages a stream holds on some subjects, and ending() prints what settle() returned:
<?php
// lib.php: the helpers every script here shares.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\JetStreamContext;
use IDCT\NATS\JetStream\Models\StreamInfo;
/** The client version installed here, as Composer reports it. */
function clientVersion(): string
{
$version = InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client');
return (string) $version;
}
/** Connects to one server, quietly. */
function connect(string $url, mixed ...$options): NatsClient
{
$client = new NatsClient(new NatsOptions(...['servers' => [$url], ...$options]));
$client->connect()->await();
return $client;
}
/** "s215, nats-server 2.15.3": the name and version the server's INFO reports. */
function server(NatsClient $client): string
{
$info = $client->serverInfo();
return sprintf('%s, nats-server %s', $info?->serverName, $info?->version);
}
/** Deletes the stream if it is there, then creates it. */
function fresh(
JetStreamContext $js, string $name, array $subjects, array $options = [],
): StreamInfo
{
try {
$js->deleteStream($name)->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
return $js->createStream($name, $subjects, $options)->await();
}
/** How many messages a stream holds on the subjects that match $filter. */
function countOn(NatsClient $client, string $stream, string $filter): int
{
$reply = $client->request(
'$JS.API.STREAM.INFO.' . $stream,
json_encode(['subjects_filter' => $filter]),
)->await();
$subjects = json_decode($reply->payload, true)['state']['subjects'] ?? [];
return array_sum($subjects);
}
/** What settle() returned, on one line (2.41.0 and later). */
function ending(object $end): string
{
$failure = $end->failure === null ? 'null' : brief($end->failure);
return sprintf('nothingSent %s, pubAck batchCount %s, failure %s',
show($end->nothingSent()), show($end->pubAck?->batchCount), $failure);
}
/** A PHP value as it would read in JSON, enum cases by name. */
function show(mixed $value): string
{
if ($value instanceof \UnitEnum) {
return $value->name;
}
if (is_array($value) && array_is_list($value)) {
return '[' . implode(', ', $value) . ']';
}
return json_encode($value, JSON_UNESCAPED_SLASHES);
}
/** Seconds since $start (an hrtime(true) value), as "12.345 s". */
function since(int|float $start): string
{
return sprintf('%6.3f s', (hrtime(true) - $start) / 1e9);
}
/** An exception as one line: its short class name, err_code when it has one, message. */
function brief(\Throwable $e): string
{
$class = (new \ReflectionClass($e))->getShortName();
$code = $e instanceof JetStreamException && $e->getErrCode() !== null
? ' (err_code ' . $e->getErrCode() . ')'
: '';
return $class . $code . ': ' . $e->getMessage();
}
/** Prints a line, wrapped at 82 characters, continuation lines indented. */
function say(string $line): void
{
echo wordwrap($line, 82, "\n ", true), "\n";
}
To delay the flow acks without touching the server, hiccup-proxy.php sits between the client and the server. When the client publishes to the subject hiccup, the proxy holds everything the server sends on that connection for a fixed time, then passes it on in order. Nothing is lost and the connection stays open; the replies only come late. It runs as a separate PHP process:
<?php
// hiccup-proxy.php: a TCP proxy that holds the server's replies for a while.
// php hiccup-proxy.php <listen port> <server host:port> <hold s> <lifetime s>
// When the client publishes to the subject "hiccup", all the server sends on
// that connection in the next <hold> seconds is held, then passed on in order.
// Nothing is dropped and the connection stays open: the replies only come late.
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, $hold, $seconds] = $argv;
function relay(Socket $client, Socket $server, float $hold): void
{
$until = 0.0; // hold the server's bytes until then (hrtime, seconds)
async(function () use ($client, $server, $hold, &$until): void {
try {
while (($bytes = $client->read()) !== null) {
if ($until === 0.0 && str_contains($bytes, ' hiccup ')) {
$until = hrtime(true) / 1e9 + $hold;
}
$server->write($bytes);
}
$server->end();
} catch (\Throwable) {
$server->close();
}
});
try {
while (($bytes = $server->read()) !== null) {
$wait = $until - hrtime(true) / 1e9;
if ($wait > 0) {
delay($wait);
}
$client->write($bytes);
}
$client->end();
} catch (\Throwable) {
$client->close();
}
}
$listener = listen("127.0.0.1:$port", (new BindContext())->withTcpNoDelay());
async(function () use ($listener, $target, $hold): void {
while ($client = $listener->accept()) {
$server = connect($target, (new ConnectContext())->withTcpNoDelay());
async(fn() => relay($client, $server, (float) $hold));
}
});
printf("127.0.0.1:%s -> %s, holds the replies for %s s after a hiccup, for %s s\n",
$port, $target, $hold, $seconds);
delay((float) $seconds);
exit(0);
The commands, in the order of this post. We ran the proxies and all three scripts in a 2.41.0 install, then settle.php in a 2.40.4 install, and refused.php and delete.php in a 2.40.0 install:
(cd servers && docker compose up -d)
composer install
php hiccup-proxy.php 15130 127.0.0.1:15125 1.5 900 &
php hiccup-proxy.php 15131 127.0.0.1:15125 3 900 &
php hiccup-proxy.php 15132 127.0.0.1:15124 1.5 900 &
php settle.php nats://127.0.0.1:15130
php settle.php nats://127.0.0.1:15131
php settle.php nats://127.0.0.1:15132
php refused.php
php refused.php nats://127.0.0.1:15114
php delete.php
php delete.php nats://127.0.0.1:15114
An upload whose flow acks come late
settle.php starts a batch with an ack timeout of one second and sends up to 1,000 parts to a subject of its own. After part 50 it publishes to hiccup, so the proxy holds the server's replies for 1.5 seconds. Then it cleans up: with settle() where the release has it, with one more add() where it does not. It purges what the upload stored and finally starts the next batch on the same stream, trying again every quarter of a second while the server refuses it:
<?php
// settle.php: a fast-ingest upload whose flow acks come late, then the cleanup,
// then the next batch on the same stream (the server allows one in flight).
// php settle.php <server url>, through hiccup-proxy.php
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\Exception\NatsThrowable;
use function Amp\delay;
$client = connect($argv[1]);
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
fresh($js, 'UPLOADS', ['uploads.>'], ['allow_batched' => true]);
$fast = $js->fastPublisher(ackTimeoutMs: 1000);
$subject = 'uploads.' . $fast->batchId();
$start = hrtime(true);
try {
for ($part = 1; $part <= 1000; $part++) {
if ($part === 51) {
$client->publish('hiccup', '')->await(); // the proxy holds replies now
}
$fast->add($subject, "part $part")->await();
}
$fast->commit($subject, 'end')->await();
} catch (NatsThrowable $e) {
say(since($start) . " add($part) threw " . brief($e));
}
if (method_exists($fast, 'settle')) {
for ($try = 1; ; $try++) {
try {
$end = $fast->settle()->await();
say(since($start) . " settle() $try: " . ending($end));
break;
} catch (NatsThrowable $e) {
say(since($start) . " settle() $try threw " . brief($e));
}
}
} else {
try {
$fast->add($subject, 'one more')->await();
} catch (NatsThrowable $e) {
say(since($start) . ' add() again: ' . brief($e));
}
}
$held = countOn($client, 'UPLOADS', $subject);
echo since($start), " the upload holds $held messages\n";
$js->purgeStream('UPLOADS', ['filter' => $subject])->await();
$held = countOn($client, 'UPLOADS', $subject);
echo since($start), " purged, the upload holds $held messages\n";
// The next batch on the stream: refused with 10211 while this one is in flight.
for ($try = 1; ; $try++) {
try {
$next = $js->fastPublisher();
$next->add('uploads.next', 'part 1')->await();
$ack = $next->commit('uploads.next', 'end')->await();
echo since($start), " the next batch committed {$ack->batchCount} messages",
" at try $try\n";
break;
} catch (JetStreamException $e) {
if ($try === 1) {
say(since($start) . ' the next batch: ' . brief($e));
}
delay(0.25);
}
}
$client->disconnect()->await();
With 2.40.4, through the first proxy, in front of the 2.15.3 server with the batch limit:
one215, nats-server 2.15.3, client v2.40.4
1.012 s add(200) threw TimeoutException: Fast batch 664393c1415feca5ded788d9:
message 200 waited 1000 ms for a flow ack; ack sequence 0
1.012 s add() again: JetStreamException: Fast batch 664393c1415feca5ded788d9 is
closed: it timed out waiting for the server
1.507 s the upload holds 200 messages
1.508 s purged, the upload holds 0 messages
1.509 s the next batch: JetStreamException (err_code 10211): batch publish too
many inflight
10.833 s the next batch committed 2 messages at try 38
With 2.41.0, the same command:
one215, nats-server 2.15.3, client v2.41.0
1.011 s add(200) threw TimeoutException: Fast batch 80701c0218a662a1b08da907:
message 200 waited 1000 ms for a flow ack; ack sequence 0
1.506 s settle() 1: nothingSent false, pubAck batchCount 200, failure null
1.507 s the upload holds 200 messages
1.508 s purged, the upload holds 0 messages
1.512 s the next batch committed 2 messages at try 1

- Both releases time out the same way.
add(200)waited for a flow ack that the proxy held and gave up at 1.012 s with 2.40.4 and 1.011 s with 2.41.0. With the default flow of 100 and two outstanding acks, message 200 is the first one that has to wait, and "ack sequence 0" shows that no flow ack had arrived. - 2.40.4 knows nothing more after that. One more
add()fails at once: the batch is closed. The purge worked here, since every part had reached the server by then, but the client never heard from the server about the batch. And the server still had the batch open: the next batch on the stream was refused with 10211 until 10.833 s, about nine seconds after the purge. That fits the server's idle abandonment, 10 seconds by default. - 2.41.0 got the server's word.
settle()returned as soon as the proxy let the replies through, at 1.506 s, with a PubAck whosebatchCountis 200 and no failure: the server had stored every part the publisher sent, and no more of the batch would arrive. After the purge, the next batch committed at its first try.
On 2.14.10, through the third proxy, the picture was the same: the next batch committed at 10.834 s with 2.40.4 and at 1.511 s with 2.41.0. The chart shows all four runs.
When settle() itself gets no answer
The second proxy holds the replies for three seconds instead of 1.5, longer than the timeouts of add() and the first settle() together. The script calls settle() until it returns:
one215, nats-server 2.15.3, client v2.41.0
1.011 s add(200) threw TimeoutException: Fast batch 77163b9b3fd5f72eb2f1f27c:
message 200 waited 1000 ms for a flow ack; ack sequence 0
2.012 s settle() 1 threw TimeoutException: Fast batch 77163b9b3fd5f72eb2f1f27c:
no reply to the EOB commit at batch sequence 201 within 1000 ms; ack sequence 0
3.005 s settle() 2: nothingSent false, pubAck batchCount null, failure
JetStreamException (err_code 10208): batch publish ID unknown
3.006 s the upload holds 200 messages
3.007 s purged, the upload holds 0 messages
3.008 s the next batch committed 2 messages at try 1
The first settle() gave up after its own ack timeout of one second, as documented. The second sent a new EOB commit at the next batch sequence, and the server answered it with 10208, "batch publish ID unknown". The batch had not been idle for 10 seconds, so the server no longer knew it because the first EOB commit had already ended it; that answer was still in the proxy when the first settle() gave up. So a retried settle() can report a failure for a batch whose parts were all stored, as the count of 200 shows. For a cleanup that is enough, because the server stores nothing more of the batch either way. When you need the count, read it from the stream, not only from failure.
What settle() returns in the other cases
settle() also answers when the publisher already knows the end: after a commit, or after a call that threw the end. refused.php shows both, and it doubles as the test of 2.40.3's fix. It sends a batch of six into a stream that takes messages of up to 64 bytes, and the fourth message is 100 bytes long, so the server refuses it before it reaches the batch (err_code 10054). Once in gap mode fail, the default, and once in gap mode ok:
<?php
// refused.php: a batch of six into a stream that takes messages of up to 64 bytes;
// message 4 is 100 bytes, so the server refuses it before it reaches the batch.
// Gap mode fail (the default), then gap mode ok.
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NATS\Exception\FastBatchException;
use IDCT\NATS\Exception\NatsThrowable;
$client = connect($argv[1] ?? 'nats://127.0.0.1:15115');
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
foreach ([false, true] as $continueOnGap) {
$options = ['allow_batched' => true, 'max_msg_size' => 64];
fresh($js, 'READINGS', ['readings.>'], $options);
echo "\ngap mode ", $continueOnGap ? 'ok' : 'fail', "\n";
$fast = $js->fastPublisher(
continueOnGap: $continueOnGap,
onError: function (FastBatchException $e): void {
say(" onError: message {$e->batchSequence}: " . brief($e));
},
);
$start = hrtime(true);
try {
for ($n = 1; $n <= 5; $n++) {
$payload = $n === 4 ? str_repeat('x', 100) : "reading $n";
$fast->add('readings.t1', $payload)->await();
}
$ack = $fast->commit('readings.t1', 'reading 6')->await();
echo since($start), " commit(6) returned, batchCount {$ack->batchCount}\n";
} catch (NatsThrowable $e) {
say(since($start) . " call $n threw " . brief($e));
if ($e instanceof FastBatchException) {
echo ' its pubAck: batchCount ', show($e->pubAck?->batchCount), "\n";
say(' its previous: ' . brief($e->getPrevious()));
}
}
echo ' publisher closed: ', show($fast->isClosed()), "\n";
if (method_exists($fast, 'settle')) {
say(' settle(): ' . ending($fast->settle()->await()));
}
$stored = [];
$last = $js->getStream('READINGS')->await()->messages();
for ($seq = 1; $seq <= $last; $seq++) {
$message = $js->getStreamMessage('READINGS', $seq)->await();
$stored[] = "'$message->payload'";
}
say(' stream: ' . implode(', ', $stored));
}
// A publisher that never sent a message, and one whose batch was committed.
if (method_exists($fast, 'settle')) {
echo "\nsettle() on a fresh publisher\n";
say(' ' . ending($js->fastPublisher()->settle()->await()));
echo "settle() after a commit\n";
$fast = $js->fastPublisher();
$fast->add('readings.t2', 'reading 1')->await();
$fast->commit('readings.t2', 'reading 2')->await();
say(' ' . ending($fast->settle()->await()));
}
$client->disconnect()->await();
With 2.40.0:
s215, nats-server 2.15.3, client v2.40.0
gap mode fail
0.001 s call 6 threw JetStreamException (err_code 10054): message size exceeds
maximum allowed
publisher closed: true
stream: 'reading 1', 'reading 2', 'reading 3'
gap mode ok
0.001 s call 6 threw JetStreamException (err_code 10054): message size exceeds
maximum allowed
publisher closed: true
stream: 'reading 1', 'reading 2', 'reading 3', 'reading 5', 'reading 6'
With 2.41.0:
s215, nats-server 2.15.3, client v2.41.0
gap mode fail
0.001 s call 6 threw FastBatchException: Fast batch 0e8043249e7fd6a8544c7f03
ended at batch sequence 3 before its commit: Fast batch 0e8043249e7fd6a8544c7f03:
message 4 was refused: message size exceeds maximum allowed
its pubAck: batchCount 3
its previous: FastBatchException (err_code 10054): Fast batch
0e8043249e7fd6a8544c7f03: message 4 was refused: message size exceeds maximum
allowed
publisher closed: true
settle(): nothingSent false, pubAck batchCount 3, failure FastBatchException:
Fast batch 0e8043249e7fd6a8544c7f03 ended at batch sequence 3 before its commit:
Fast batch 0e8043249e7fd6a8544c7f03: message 4 was refused: message size exceeds
maximum allowed
stream: 'reading 1', 'reading 2', 'reading 3'
gap mode ok
onError: message 4: FastBatchException (err_code 10054): Fast batch
f7b64ec2109cb7475dacaabb: message 4 was refused: message size exceeds maximum
allowed
onError: message 5: FastBatchException: Fast batch f7b64ec2109cb7475dacaabb: gap
at batch sequence 5, messages 4 to 4 were lost
0.001 s commit(6) returned, batchCount 6
publisher closed: true
settle(): nothingSent false, pubAck batchCount 6, failure null
stream: 'reading 1', 'reading 2', 'reading 3', 'reading 5', 'reading 6'
settle() on a fresh publisher
nothingSent true, pubAck batchCount null, failure null
settle() after a commit
nothingSent false, pubAck batchCount 2, failure null
- Gap mode
okwas the real bug. On 2.40.0 the commit threw the server's 10054 and closed the publisher, while the stream shows that the server stored messages 1, 2, 3, 5 and 6 and committed the batch. The caller got an error for a batch that had succeeded. From 2.40.3 on,onErrorreceives the refusal of message 4, the commit returns a PubAck withbatchCount6, andsettle()reports no failure. The server also reported a gap at message 5, which reachedonErroras a second notice. Note thatbatchCountis the commit's batch sequence, not the number of messages stored: five are in the stream. - Gap mode
failnow says how far the batch got. 2.40.0 threw a bareJetStreamExceptionwith 10054 and no count. 2.41.0 throws aFastBatchExceptionwhosepubAcksays the batch ended at batch sequence 3, with the refusal as its previous exception. Afterwardssettle()returns that same end without sending anything. - The two quiet cases. A publisher that never sent a message returns
nothingSent()true, and one whose batch was committed returns the commit's PubAck with no failure.
The same script against 2.14.10 printed the same lines with both releases, apart from the batch ids. Here the refused message had two more after it, so the answer came at once. The release notes say that when nothing follows a refused message, the PubAck comes with the call's first ping, a third of the ack timeout later (3.3 s at the default of 10 s). We did not run that case, nor a sealed stream or an account limit. The release notes say the same of the limit errors: they were read in the server's source, not run.
2.40.1: no chunks left behind
An Object Store object is a set of chunk messages plus a meta message that names them. When an object is deleted or overwritten, the client looks up the previous revision and purges its chunks. Until 2.40.1 that lookup could reach the server after the new record and read that one instead, so the old chunks stayed in the bucket's stream with nothing naming them. The release notes measured 60 rounds: delete() left the chunks behind every time, an overwrite with an empty object 59 times. delete.php repeats both five times with a four-chunk object:
<?php
// delete.php: delete() and an overwrite with an empty object, five rounds each,
// and how many chunks of the previous revision each round leaves in the bucket.
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NATS\Exception\JetStreamException;
$client = connect($argv[1] ?? 'nats://127.0.0.1:15115');
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
$store = $js->objectStore('files');
try {
$store->deleteBucket()->await();
} catch (JetStreamException) {
// first run: no bucket yet
}
$store->create()->await();
$data = random_bytes(4 * 128 * 1024); // four chunks of 128 KiB
$chunks = fn(): int => countOn(
$client, $store->streamName(), $store->chunkPrefix() . '>',
);
$rounds = [
'delete()' => fn(string $name) => $store->delete($name)->await(),
'empty overwrite' => fn(string $name) => $store->put($name, '')->await(),
];
foreach ($rounds as $what => $second) {
$left = [];
for ($round = 1; $round <= 5; $round++) {
$before = $chunks();
$name = "report-$round.bin";
$store->put($name, $data)->await(); // four chunks and a meta
$second($name);
$left[] = $chunks() - $before;
}
printf("%-16s chunks left behind, per round: %s\n", $what, implode(' ', $left));
}
$client->disconnect()->await();
With 2.40.0, then with 2.41.0:
s215, nats-server 2.15.3, client v2.40.0
delete() chunks left behind, per round: 4 4 4 4 4
empty overwrite chunks left behind, per round: 4 4 4 4 4
s215, nats-server 2.15.3, client v2.41.0
delete() chunks left behind, per round: 0 0 0 0 0
empty overwrite chunks left behind, per round: 0 0 0 0 0
Every round on 2.40.0 left four chunks in the stream, and no round on 2.41.0 did. 2.14.10 gave the same counts. The fix reads the previous revision before it writes the new meta, so delete() now pays one more round trip, as nats.go's Delete does. Chunks orphaned by earlier releases stay where they are: 2.40.1 stops new ones but does not remove old ones.
The same release fixes two more Object Store failures, which we did not reproduce. When the publish of the meta timed out or lost its connection, the client purged the new chunks, although the server may already have stored the meta: the name then pointed at chunks that no longer existed, and get() failed with "Incomplete object download". Such a failure now purges nothing and is passed on as it is. And a failed cleanup of the previous revision no longer fails a write that was stored.
2.40.2 and 2.40.4, from the release notes
We did not run these two, so this is what their release notes say.
2.40.2: a stalled add() waits on across a reconnect. A stalled add() has already sent its message, which keeps its place in the batch. Until 2.40.2, a connection that broke during the stall made the call throw and leave the batch open with the message in it, while a message that could not be sent at all failed with the same ConnectionException. A caller could not tell the two apart: sending again stored the stalled message twice, and not sending lost the other one. Now the stall waits while the client reconnects, within the same ack timeout, and returns once the ack arrives. A reconnect that takes longer ends with a TimeoutException and a closed publisher, which is exactly the case settle() is for. The release notes add that the reconnect cases ran over scripted connections in the unit tests, and that a real fatal -ERR or a failover against a live server was not tested.
2.40.4: requestMany() keeps collecting. requestMany() sends one request and collects the replies of every responder. Since 2.30.0, a permission error for the request's subject ended the collection at once, and the call returned what it had as if it were complete. The server names only the subject in that error, not the publish it refused, so once a reply has arrived, the error must belong to another publish to the same subject. A requestMany() with a reply now runs on to its usual end. The developer measured it against nats-server 2.12.15, 2.14.10 and 2.15.3: a two-responder request whose subject was refused between the two replies returned only the first reply after about 0.8 s, and now returns both after about 1.5 s. A call that has collected nothing yet is still refused with a PermissionViolationException.
Quality gates
From the 2.41.0 release notes: PHPStan level 8; 4597 unit tests on PHP 8.2 to 8.5, 32 more than in 2.40.4, of which 23 are for settle(); 199 live integration tests against the nats-server 2.12 fixture stack, 15 of them skipped there because they need 2.14, and 196 passing in a second run against 2.14, where nothing may skip. The new live test settles an open batch on a real server and checks that a second settle() returns the same end. All 54 Behat scenarios and all 47 runnable examples pass, every changed line is covered, and total coverage is 99.14%. In the review, each of the last round's two fixes was taken out of a copy of the code, one at a time, and each turned its test red.
Two test-only changes ship with it. #324 brings the lame-duck tests in line with 2.37.1, which stopped failing over at a lame-duck notice (#265). #335 pins the default upload window of objectStore(), the gap our last post mentioned (#333). The four patch releases added 13, 9, 9 and 2 unit tests, and 2.40.1 and 2.40.3 brought new live tests.
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.