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

php-nats-jetstream-client 2.35: durable stream sourcing

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

2.35.0 adds AckPolicy::FlowControl and StreamSource::consumer(): a stream can copy a NATS work queue through a consumer of your own. We ran it on four server versions, across JetStream domains and through a link that drops.

idct/php-nats-jetstream-client 2.35.0 is out, and it lets the typed builders set up durable stream sourcing, the part of nats-server 2.14 that copies a work queue or an Interest stream into another stream without losing messages. Two additions do it: AckPolicy::FlowControl, the ack policy of the consumer the copy runs through, and StreamSource::consumer(), which names that consumer in a source or a mirror. A 2.14 server can also make such a consumer by itself; naming your own is for when you want to own its configuration and its lifetime.

Our last post on the client covered 2.34.0, and 2.35.0 is the only release since. We ran every example below on PHP 8.5.9 against nats-server 2.14.10, 2.12.15, 2.11.17 and 2.10.29 in Docker, with 2.35.0 from Packagist and, for the comparison, 2.34.0. The output is pasted as it came out. We also ran the one combination the release says it did not run live, a named consumer in another JetStream domain, and cut the link between a leaf node and its hub in the middle of the copy.

Upgrading

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

Existing calls need no change. Before you use the new parts, check these:

  • Both need nats-server 2.14, and the client does not check the version. 2.12 refuses a flow_control consumer and a source that names a consumer with a 400. 2.10 and 2.11 refuse the consumer too, but they accept the source and quietly drop the consumer field. We show all four below, with the check that catches the quiet case.
  • AckPolicy has a fourth case. A match over it without a default arm has to handle FlowControl.
  • StreamSource::toArray() can now throw, but only when consumer() is combined with startSeq(), startTime() or filterSubject(). Code that does not call consumer() is not affected.

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

Why a work queue needed a new kind of consumer

A stream can source or mirror another stream: an aggregate collects several streams, a region keeps a copy of another region's data, a hub collects what its leaf nodes record. The server does this through an ephemeral push consumer with the ack policy none, and for a Limits stream it still does. That is fine there: when the copy misses a message, the server asks again from the sequence it missed, and the message is still there.

ADR-60, the design behind this part of 2.14, explains why that breaks for the other two retention policies. A WorkQueue or Interest stream removes a message once it counts as acknowledged, and with none it counts as acknowledged as soon as it is sent. If the copy never arrives, the message is gone from both sides. An Interest stream has a second problem: an ephemeral consumer disappears while the two servers are disconnected, and with it the interest that keeps messages in the stream. The nats-server 2.14.0 release notes list sourcing and mirroring from such streams as newly supported.

The fix is a durable consumer with a new ack policy, flow_control. The sourcing server answers the consumer's flow control messages with the last stream and delivery sequence it has stored, and the origin acknowledges up to there. A message leaves a work queue only after the copy is stored. The server either makes that consumer itself, or uses one you created and named in the source. The second way is what the client's builders could not express:

GitHub issue 280 of php-nats-jetstream-client, closed by pull request 282: the typed builders had no flow_control ack policy and StreamSource could not name a consumer

Raw arrays passed to createConsumer() and createStream() already worked against 2.14, as the issue notes. With the typed API, 2.34.0 had neither piece. before.php asks the installed version for both:

php
<?php
// before.php: the two additions, asked for on the installed version of the client.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use Composer\InstalledVersions;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;

$package = 'idct/php-nats-jetstream-client';
echo $package, ' ', InstalledVersions::getPrettyVersion($package), PHP_EOL;

$source = fn(): array => StreamSource::source('JOBS')
    ->consumer('JOBS_ARCHIVE', 'deliver.jobs.archive')
    ->toArray();
$checks = [
    "AckPolicy::tryFrom('flow_control')" => fn(): string =>
        var_export(AckPolicy::tryFrom('flow_control'), true),
    'StreamSource::consumer()' => fn(): string => json($source()),
];
foreach ($checks as $label => $check) {
    try {
        line("   $label: " . $check());
    } catch (\Error $e) {
        line("   $label: " . $e::class . ': ' . $e->getMessage());
    }
}
text
idct/php-nats-jetstream-client v2.34.0
   AckPolicy::tryFrom('flow_control'): NULL
   StreamSource::consumer(): Error: Call to undefined method
     IDCT\NATS\JetStream\Configuration\StreamSource::consumer()
text
idct/php-nats-jetstream-client v2.35.0
   AckPolicy::tryFrom('flow_control'):
     \IDCT\NATS\JetStream\Enum\AckPolicy::FlowControl
   StreamSource::consumer(): {"name": "JOBS", "consumer": {"name": "JOBS_ARCHIVE",
     "deliver_subject": "deliver.jobs.archive"}}

A proof of concept you can run

Four standalone servers (2.14, 2.12, 2.11, 2.10), a hub with a leaf node that runs its own JetStream, and a second hub and leaf node whose link runs through a proxy in one of the scripts:

yaml
services:
  nats-2-14:
    image: nats:2.14-alpine
    command: ["-js", "-n", "nats-2-14"]
    ports: ["14514:4222"]
  nats-2-12:
    image: nats:2.12-alpine
    command: ["-js", "-n", "nats-2-12"]
    ports: ["14512:4222"]
  nats-2-11:
    image: nats:2.11-alpine
    command: ["-js", "-n", "nats-2-11"]
    ports: ["14511:4222"]
  nats-2-10:
    image: nats:2.10-alpine
    command: ["-js", "-n", "nats-2-10"]
    ports: ["14510:4222"]
  hub:
    image: nats:2.14-alpine
    command: ["-c", "/etc/nats/hub.conf"]
    volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
    ports: ["14520:4222"]
  edge:
    image: nats:2.14-alpine
    command: ["-c", "/etc/nats/edge.conf"]
    volumes: ["./edge.conf:/etc/nats/edge.conf:ro"]
    ports: ["14521:4222"]
    depends_on: [hub]
  wan-hub:
    image: nats:2.14-alpine
    command: ["-c", "/etc/nats/hub.conf"]
    volumes: ["./hub.conf:/etc/nats/hub.conf:ro"]
    ports: ["14530:4222", "127.0.0.1:14531:7422"]
  wan-shop:
    image: nats:2.14-alpine
    command: ["-c", "/etc/nats/wan-shop.conf"]
    volumes: ["./wan-shop.conf:/etc/nats/wan-shop.conf:ro"]
    ports: ["14533:4222"]
    extra_hosts: ["host.docker.internal:host-gateway"]
    networks: [wan] # not the hub's network: its only way there is the proxy

networks:
  wan: {}

The hub and the two leaf nodes. The second hub, wan-hub, uses the same hub.conf:

text
# hub.conf: JetStream under the domain "hub", and a port for leaf nodes.
port: 4222
server_name: hub

jetstream {
  domain: hub
}

leafnodes {
  port: 7422
}
text
# edge.conf: a leaf node with a JetStream of its own, under the domain "edge".
port: 4222
server_name: edge

jetstream {
  domain: edge
}

leafnodes {
  remotes: [
    { url: "nats-leaf://hub:7422" }
  ]
}
text
# wan-shop.conf: a leaf node with a JetStream of its own, under the domain "shop". It
# reaches the hub only through the TCP proxy that link.php runs on the Docker host.
port: 4222
server_name: shop

jetstream {
  domain: shop
}

leafnodes {
  remotes: [
    { url: "nats-leaf://host.docker.internal:14532" }
  ]
}
json
{
    "require": {
        "php": "^8.2",
        "idct/php-nats-jetstream-client": "^2.35"
    }
}

Every script loads a few shared helpers. waitFor() polls a stream until it holds a number of messages, and payloads() lists what a stream stores:

php
<?php
// lib.php: the helpers every script here shares.
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\JetStream\JetStreamContext;

use function Amp\delay;

function connect(string $url): NatsClient
{
    $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);

    return $client;
}

/** Deletes what an earlier run left behind, so every run starts the same way. */
function dropStreams(JetStreamContext $js, string ...$streams): void
{
    foreach ($streams as $stream) {
        try {
            $js->deleteStream($stream)->await();
        } catch (JetStreamException) {
            // not there: nothing to delete
        }
    }
}

function messages(JetStreamContext $js, string $stream): int
{
    return (int) ($js->getStream($stream)->await()->raw['state']['messages'] ?? -1);
}

/** Waits until $stream holds $expected messages, or $seconds pass. */
function waitFor(
    JetStreamContext $js,
    string $stream,
    int $expected,
    float $seconds = 10,
): int {
    $deadline = microtime(true) + $seconds;
    do {
        $count = messages($js, $stream);
        if ($count >= $expected) {
            break;
        }
        delay(0.2);
    } while (microtime(true) < $deadline);

    return $count;
}

/** The payloads stored in $stream, oldest first. */
function payloads(JetStreamContext $js, string $stream): string
{
    $state = $js->getStream($stream)->await()->raw['state'] ?? [];
    if (($state['messages'] ?? 0) === 0) {
        return '(empty)';
    }
    $payloads = [];
    for ($seq = $state['first_seq']; $seq <= $state['last_seq']; $seq++) {
        $payloads[] = $js->getStreamMessage($stream, $seq)->await()->payload;
    }

    return implode(' ', $payloads);
}

function describe(JetStreamException $e): string
{
    return sprintf('%d, err_code %s: %s', $e->getCode(), $e->getErrCode() ?? '-',
        $e->getMessage());
}

/** JSON with a space after each colon and comma, so that line() can wrap it. */
function json(array $value): string
{
    $text = json_encode($value, JSON_UNESCAPED_SLASHES);

    return str_replace(['":', ',"'], ['": ', ', "'], $text);
}

/** Prints $text wrapped at 86 columns, with the next lines indented. */
function line(string $text, string $indent = '     '): void
{
    echo wordwrap($text, 86, "\n" . $indent), PHP_EOL;
}

The commands, in the order of this post:

bash
docker compose up -d
composer install
php before.php
php managed.php
php archive.php
php edge.php
php link.php
php rules.php
php pitfalls.php
php interest.php
php older.php nats://127.0.0.1:14510    # nats-server 2.10
php older.php nats://127.0.0.1:14511    # 2.11
php older.php nats://127.0.0.1:14512    # 2.12
php older.php nats://127.0.0.1:14514    # 2.14

What a 2.14 server does by itself

Nothing new is needed in the client for the server-managed way. managed.php sources a work queue with the plain StreamSource::source() that existed before:

php
<?php
// managed.php: a 2.14 server sources a work queue by itself, through a consumer it adds.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\JetStream\Configuration\StreamConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\RetentionPolicy;

use function Amp\delay;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14514');
$js = $client->jetStream();
dropStreams($js, 'ARCHIVE', 'JOBS');

$js->addStream(StreamConfiguration::create('JOBS')
    ->subjects('jobs.>')
    ->retention(RetentionPolicy::WorkQueue))->await();
$js->createStream('ARCHIVE', [], [
    'sources' => [StreamSource::source('JOBS')->toArray()],
])->await();

foreach ([1, 2, 3] as $id) {
    $js->publish('jobs.email', "job-$id")->await();
}
$state = function (string $when) use ($js): void {
    printf("%sARCHIVE: %s | JOBS: %d left\n", $when, payloads($js, 'ARCHIVE'),
        messages($js, 'JOBS'));
};
waitFor($js, 'ARCHIVE', 3);
$state('At once:    ');
delay(2);
$state('2 s later:  ');

echo "Consumers on JOBS:\n";
foreach ($js->listConsumers('JOBS')->await() as $consumer) {
    $config = $consumer->raw['config'];
    $source = array_filter(
        $config['metadata'] ?? [],
        fn(string $key): bool => str_starts_with($key, '_nats.src.'),
        ARRAY_FILTER_USE_KEY,
    );
    printf("   %s, ack_policy %s, durable %s\n", $consumer->name, $config['ack_policy'],
        isset($config['durable_name']) ? 'yes' : 'no');
    line('   metadata ' . json($source));
}

$js->deleteStream('ARCHIVE')->await();
delay(1);
$consumers = $js->listConsumers('JOBS')->await();
printf("After deleting ARCHIVE: %d consumers on JOBS\n", count($consumers));

$client->disconnect()->await();
text
Connected to nats-2-14, nats-server 2.14.10
At once:    ARCHIVE: job-1 job-2 job-3 | JOBS: 3 left
2 s later:  ARCHIVE: job-1 job-2 job-3 | JOBS: 0 left
Consumers on JOBS:
   JS_SRC_3laPg7Dz, ack_policy flow_control, durable yes
   metadata {"_nats.src.acc": "$G", "_nats.src.stream": "ARCHIVE"}
After deleting ARCHIVE: 0 consumers on JOBS
  • The server made a durable consumer, named JS_SRC_ plus a suffix, with the ack policy flow_control and metadata that names the stream it copies for, as ADR-60 describes.
  • The work queue keeps a message until the copy is acknowledged. Right after the archive stored the three jobs, the work queue still held them. Two seconds later it was empty. On an idle stream the acknowledgement comes with the next flow control exchange, which the consumer's heartbeat triggers.
  • The consumer goes with the sourcing stream. After ARCHIVE is deleted, JOBS has no consumer left. ADR-60 calls this deletion best effort, so check for leftovers if a delete fails.

A consumer of your own

Naming your own consumer gives you its configuration and its lifecycle. archive.php creates it on the work queue and has the archive name it. Then it pauses the consumer, deletes the archive under it and picks up again with a new archive.

php
<?php
// archive.php: a consumer of your own copies a work queue into an archive stream.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\JetStream\Configuration\ConsumerConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;
use IDCT\NATS\JetStream\Enum\RetentionPolicy;

use function Amp\delay;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14514');
$js = $client->jetStream();
dropStreams($js, 'ARCHIVE', 'JOBS');
$js->addStream(StreamConfiguration::create('JOBS')
    ->subjects('jobs.>')
    ->retention(RetentionPolicy::WorkQueue))->await();

$publish = function (int ...$ids) use ($js): void {
    foreach ($ids as $id) {
        $js->publish('jobs.email', "job-$id")->await();
    }
};
$state = function (string $when) use ($js): void {
    line(sprintf('   %sARCHIVE: %s | JOBS: %d left', $when, payloads($js, 'ARCHIVE'),
        messages($js, 'JOBS')), '               ');
};

echo "1. The consumer, on the origin:\n";
$consumer = $js->addConsumer('JOBS', ConsumerConfiguration::create()
    ->durable('JOBS_ARCHIVE')
    ->deliverSubject('deliver.jobs.archive')
    ->ackPolicy(AckPolicy::FlowControl))->await();
$config = $consumer->raw['config'];
printf("   ack_policy %s, flow_control %s, idle_heartbeat %d s\n",
    $config['ack_policy'],
    json_encode($config['flow_control'] ?? null), ($config['idle_heartbeat'] ?? 0) / 1e9);
printf("   max_ack_pending %d, max_deliver %d (set by the server)\n",
    $config['max_ack_pending'], $config['max_deliver']);

echo "2. The archive names it, with the same deliver subject:\n";
$source = StreamSource::source('JOBS')->consumer('JOBS_ARCHIVE', 'deliver.jobs.archive');
$info = $js->createStream('ARCHIVE', [], ['sources' => [$source->toArray()]])->await();
line('   stored source: ' . json($info->raw['config']['sources'][0]));

echo "3. Three jobs:\n";
$publish(1, 2, 3);
waitFor($js, 'ARCHIVE', 3);
$state('at once:    ');
delay(2);
$state('2 s later:  ');

echo "4. Pause the consumer for an hour, then two more jobs:\n";
$until = gmdate('Y-m-d\TH:i:s\Z', time() + 3600);
$js->pauseConsumer('JOBS', 'JOBS_ARCHIVE', $until)->await();
$publish(4, 5);
delay(3);
$state('3 s later:  ');
$js->resumeConsumer('JOBS', 'JOBS_ARCHIVE')->await();
waitFor($js, 'ARCHIVE', 5);
delay(2);
$state('resumed:    ');

echo "5. Delete the archive stream, then two more jobs:\n";
$js->deleteStream('ARCHIVE')->await();
$publish(6, 7);
delay(3);
$kept = $js->getConsumer('JOBS', 'JOBS_ARCHIVE')->await();
printf("   consumer %s is still there, %d pending | JOBS: %d left\n", $kept->name,
    $kept->raw['num_pending'] ?? -1, messages($js, 'JOBS'));

echo "6. A new archive stream with the same source:\n";
$js->createStream('ARCHIVE', [], ['sources' => [$source->toArray()]])->await();
waitFor($js, 'ARCHIVE', 2, 60);
delay(2);
$state('');

$client->disconnect()->await();
text
Connected to nats-2-14, nats-server 2.14.10
1. The consumer, on the origin:
   ack_policy flow_control, flow_control true, idle_heartbeat 1 s
   max_ack_pending 1000, max_deliver -1 (set by the server)
2. The archive names it, with the same deliver subject:
   stored source: {"name": "JOBS", "consumer": {"name": "JOBS_ARCHIVE",
     "deliver_subject": "deliver.jobs.archive"}}
3. Three jobs:
   at once:    ARCHIVE: job-1 job-2 job-3 | JOBS: 3 left
   2 s later:  ARCHIVE: job-1 job-2 job-3 | JOBS: 0 left
4. Pause the consumer for an hour, then two more jobs:
   3 s later:  ARCHIVE: job-1 job-2 job-3 | JOBS: 2 left
   resumed:    ARCHIVE: job-1 job-2 job-3 job-4 job-5 | JOBS: 0 left
5. Delete the archive stream, then two more jobs:
   consumer JOBS_ARCHIVE is still there, 2 pending | JOBS: 2 left
6. A new archive stream with the same source:
   ARCHIVE: job-6 job-7 | JOBS: 0 left
  • A durable name, a deliver subject and AckPolicy::FlowControl are enough. The server fills in flow_control, the 1 second heartbeat, max_ack_pending 1000 and max_deliver -1 by itself.
  • The stored source carries the consumer, as {name, deliver_subject}. This is the field to look for on a server whose version you do not know.
  • A paused consumer pauses the copy. Jobs 4 and 5 stayed in the work queue for the three seconds of the pause and went over after resumeConsumer(). ADR-60 names this as one of the reasons to bring your own consumer.
  • The consumer outlives the archive. With ARCHIVE deleted, JOBS_ARCHIVE stayed on the work queue with jobs 6 and 7 pending, and they waited there. A new archive that names the same consumer received exactly those two: everything before them had been acknowledged when the old archive stored it.

Across JetStream domains

The release lists one path as not run live: external() together with consumer(), which is what you need when the origin lives in another JetStream domain, for example a work queue on a leaf node that a hub copies. edge.php connects to the hub, uses the leaf node's JetStream through the domain prefix from 2.34.0, and has a second client on the leaf node publish the orders, as a local app would:

php
<?php
// edge.php: the hub sources a work queue that lives on a leaf node, in the domain edge.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\JetStream\Configuration\ConsumerConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;
use IDCT\NATS\JetStream\Enum\RetentionPolicy;

use function Amp\delay;

$hubClient = connect($argv[1] ?? 'nats://127.0.0.1:14520');
$edgeClient = connect($argv[2] ?? 'nats://127.0.0.1:14521');
$hub = $hubClient->jetStream();
$edge = $hubClient->jetStream(domain: 'edge');
printf("From the hub: JetStream domain %s, and %s through the prefix %s\n",
    $hub->accountInfo()->await()->raw['domain'] ?? '-',
    $edge->accountInfo()->await()->raw['domain'] ?? '-', $edge->apiPrefix());
dropStreams($hub, 'ARCHIVE');
dropStreams($edge, 'ORDERS');

echo "1. On the leaf node: a work queue and the consumer:\n";
$edge->addStream(StreamConfiguration::create('ORDERS')
    ->subjects('orders.>')
    ->retention(RetentionPolicy::WorkQueue))->await();
$edge->addConsumer('ORDERS', ConsumerConfiguration::create()
    ->durable('ORDERS_HUB')
    ->deliverSubject('deliver.orders.hub')
    ->ackPolicy(AckPolicy::FlowControl))->await();
echo "   ORDERS and ORDERS_HUB created in the domain edge\n";

echo "2. On the hub: ARCHIVE sources it through the edge's API:\n";
$source = StreamSource::source('ORDERS')
    ->external('$JS.edge.API')
    ->consumer('ORDERS_HUB', 'deliver.orders.hub');
$info = $hub->createStream('ARCHIVE', [], ['sources' => [$source->toArray()]])->await();
line('   stored source: ' . json($info->raw['config']['sources'][0]));

echo "3. A shop app on the leaf node publishes three orders:\n";
$local = $edgeClient->jetStream();
foreach ([1, 2, 3] as $id) {
    $ack = $local->publish('orders.created', "order-$id")->await();
    printf("   order-%d stored in %s, domain %s\n", $id, $ack->stream,
        $ack->raw['domain'] ?? '-');
}
$started = microtime(true);
$count = waitFor($hub, 'ARCHIVE', 3, 30);
printf("   ARCHIVE on the hub: %d after %.1f s\n", $count, microtime(true) - $started);
delay(2);
printf("   ARCHIVE: %s | ORDERS on the leaf node: %d left\n", payloads($hub, 'ARCHIVE'),
    messages($edge, 'ORDERS'));

$hubClient->disconnect()->await();
$edgeClient->disconnect()->await();
text
Connected to hub, nats-server 2.14.10
Connected to edge, nats-server 2.14.10
From the hub: JetStream domain hub, and edge through the prefix $JS.edge.API.
1. On the leaf node: a work queue and the consumer:
   ORDERS and ORDERS_HUB created in the domain edge
2. On the hub: ARCHIVE sources it through the edge's API:
   stored source: {"name": "ORDERS", "external": {"api": "$JS.edge.API", "deliver":
     ""}, "consumer": {"name": "ORDERS_HUB", "deliver_subject": "deliver.orders.hub"}}
3. A shop app on the leaf node publishes three orders:
   order-1 stored in ORDERS, domain edge
   order-2 stored in ORDERS, domain edge
   order-3 stored in ORDERS, domain edge
   ARCHIVE on the hub: 3 after 0.2 s
   ARCHIVE: order-1 order-2 order-3 | ORDERS on the leaf node: 0 left

It works. The source names the leaf node's API prefix and the consumer that lives there, the orders are stored in the leaf node's domain and reach the hub's ARCHIVE, and the work queue on the leaf node is empty afterwards. The server added an empty deliver prefix to the stored external, which the client did not send. Replicated streams, the other path the release did not run, are not covered here either: all our servers are single nodes.

When the link drops

The reason to use a durable consumer is what happens when the copy cannot get through. link.php runs a small TCP proxy, and the leaf node shop reaches its hub only through it. The proxy listens on 172.17.0.1, the Docker host's bridge address on Linux; change it if yours differs. The shop is on a Docker network of its own for a reason: in our first attempt it shared the hub's network, and when the proxy dropped the link, the leaf node reconnected straight to the hub's own address.

php
<?php
// link.php: the shop's link to the hub drops, orders keep coming, then the link is back.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\Configuration\ConsumerConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;
use IDCT\NATS\JetStream\Enum\RetentionPolicy;

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

// The leaf node "shop" dials the hub through this proxy, so the script can cut the link.
$linkUp = true;
$open = [];
$proxy = listen('172.17.0.1:14532');
async(function () use ($proxy, &$linkUp, &$open): void {
    while ($down = $proxy->accept()) {
        if (!$linkUp) {
            $down->close();
            continue;
        }
        $up = \Amp\Socket\connect('127.0.0.1:14531');
        array_push($open, $down, $up);
        foreach ([[$down, $up], [$up, $down]] as [$from, $to]) {
            async(function () use ($from, $to): void {
                try {
                    pipe($from, $to);
                } catch (\Throwable) {
                    // the link was cut
                } finally {
                    $to->close();
                }
            })->ignore();
        }
    }
})->ignore();

$hubClient = connect('nats://127.0.0.1:14530');
$shopClient = connect('nats://127.0.0.1:14533');
$hub = $hubClient->jetStream();
$shop = $hubClient->jetStream(domain: 'shop'); // the shop's JetStream, from the hub
$local = $shopClient->jetStream();             // the same JetStream, for the shop's apps

$reachable = function () use ($shop): bool {
    try {
        $shop->accountInfo()->await();

        return true;
    } catch (JetStreamException) {
        return false;
    }
};
$started = microtime(true);
while (!$reachable() && microtime(true) - $started < 20) {
    delay(0.5);
}
echo 'The hub reaches the shop\'s JetStream: ', $reachable() ? 'yes' : 'no', PHP_EOL;

dropStreams($hub, 'ARCHIVE');
dropStreams($local, 'ORDERS');
$local->addStream(StreamConfiguration::create('ORDERS')
    ->subjects('orders.>')
    ->retention(RetentionPolicy::WorkQueue))->await();
$local->addConsumer('ORDERS', ConsumerConfiguration::create()
    ->durable('ORDERS_HUB')
    ->deliverSubject('deliver.orders.hub')
    ->ackPolicy(AckPolicy::FlowControl))->await();
$source = StreamSource::source('ORDERS')
    ->external('$JS.shop.API')
    ->consumer('ORDERS_HUB', 'deliver.orders.hub');
$hub->createStream('ARCHIVE', [], ['sources' => [$source->toArray()]])->await();

$orders = function (int ...$ids) use ($local): void {
    foreach ($ids as $id) {
        $local->publish('orders.created', "order-$id")->await();
    }
};
$state = function (string $when) use ($hub, $local): void {
    line(sprintf('   %sARCHIVE on the hub: %s | ORDERS in the shop: %d left', $when,
        payloads($hub, 'ARCHIVE'), messages($local, 'ORDERS')));
};

echo "1. Three orders while the link is up:\n";
$orders(1, 2, 3);
waitFor($hub, 'ARCHIVE', 3);
delay(2);
$state('');

echo "2. The link drops, three more orders:\n";
$linkUp = false;
foreach ($open as $socket) {
    $socket->close();
}
delay(1);
echo '   the hub reaches the shop\'s JetStream: ', $reachable() ? 'yes' : 'no', PHP_EOL;
$orders(4, 5, 6);
delay(5);
$state('5 s later: ');

echo "3. The link is back:\n";
$linkUp = true;
$back = microtime(true);
$count = waitFor($hub, 'ARCHIVE', 6, 120);
printf("   ARCHIVE has %d messages, %.0f s after the link came back\n", $count,
    microtime(true) - $back);
delay(2);
$state('');

$proxy->close();
$hubClient->disconnect()->await();
$shopClient->disconnect()->await();
text
Connected to hub, nats-server 2.14.10
Connected to shop, nats-server 2.14.10
The hub reaches the shop's JetStream: yes
1. Three orders while the link is up:
   ARCHIVE on the hub: order-1 order-2 order-3 | ORDERS in the shop: 0 left
2. The link drops, three more orders:
   the hub reaches the shop's JetStream: no
   5 s later: ARCHIVE on the hub: order-1 order-2 order-3 | ORDERS in the shop: 3 left
3. The link is back:
   ARCHIVE has 6 messages, 1 s after the link came back
   ARCHIVE on the hub: order-1 order-2 order-3 order-4 order-5 order-6 | ORDERS in the
     shop: 0 left

While the link was down, the shop kept taking orders: its JetStream stored orders 4 to 6 locally, the hub could not reach it, and the archive stayed at three. Nothing was removed from the work queue, because nothing had been acknowledged. Within two seconds of the link coming back, the archive had all six, in order and without duplicates, and the shop's work queue was empty. This is the case the old ephemeral consumer with none could not promise.

GitHub release page of php-nats-jetstream-client v2.35.0: AckPolicy::FlowControl and StreamSource::consumer() for durable stream sourcing on NATS 2.14

What the builders refuse

ADR-60 moves the start sequence, the start time and the filter subject from the source onto the consumer. The server refuses a source that has both, with an error that names no field, so toArray() refuses the combination first. rules.php needs no server:

php
<?php
// rules.php: what the two builders produce, and what they refuse. No server needed.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\Configuration\ConsumerConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;

$show = function (string $label, callable $build): void {
    echo $label, ":\n";
    try {
        line('   ' . json($build()), '   ');
    } catch (JetStreamException $e) {
        line('   refused: ' . $e->getMessage(), '   ');
    }
};

$values = array_map(fn(AckPolicy $case): string => $case->value, AckPolicy::cases());
echo 'AckPolicy: ', implode(', ', $values), PHP_EOL;

$show('the consumer', fn() => ConsumerConfiguration::create()
    ->durable('JOBS_ARCHIVE')
    ->deliverSubject('deliver.jobs.archive')
    ->ackPolicy(AckPolicy::FlowControl)
    ->toArray());
$show('a source', fn() => StreamSource::source('JOBS')
    ->consumer('JOBS_ARCHIVE', 'deliver.jobs.archive')
    ->toArray());
$show('a mirror', fn() => StreamSource::mirror('JOBS')
    ->consumer('JOBS_MIRROR', 'deliver.jobs.mirror')
    ->toArray());
$show('a source in another domain', fn() => StreamSource::source('ORDERS')
    ->external('$JS.edge.API')
    ->consumer('ORDERS_HUB', 'deliver.orders.hub')
    ->toArray());
$show('consumer() with startSeq()', fn() => StreamSource::source('JOBS')
    ->startSeq(100)
    ->consumer('JOBS_ARCHIVE', 'deliver.jobs.archive')
    ->toArray());
$show('consumer() with startTime(), filterSubject()', fn() => StreamSource::source('JOBS')
    ->startTime('2026-11-28T00:00:00Z')
    ->filterSubject('jobs.email')
    ->consumer('JOBS_ARCHIVE', 'deliver.jobs.archive')
    ->toArray());
$show('an empty consumer name', fn() => StreamSource::source('JOBS')
    ->consumer('', 'deliver.jobs.archive'));
$show('an empty deliver subject', fn() => StreamSource::source('JOBS')
    ->consumer('JOBS_ARCHIVE', ''));
text
AckPolicy: none, all, explicit, flow_control
the consumer:
   {"durable_name": "JOBS_ARCHIVE", "deliver_subject": "deliver.jobs.archive",
   "ack_policy": "flow_control"}
a source:
   {"name": "JOBS", "consumer": {"name": "JOBS_ARCHIVE", "deliver_subject":
   "deliver.jobs.archive"}}
a mirror:
   {"name": "JOBS", "consumer": {"name": "JOBS_MIRROR", "deliver_subject":
   "deliver.jobs.mirror"}}
a source in another domain:
   {"name": "ORDERS", "external": {"api": "$JS.edge.API"}, "consumer": {"name":
   "ORDERS_HUB", "deliver_subject": "deliver.orders.hub"}}
consumer() with startSeq():
   refused: Stream source "JOBS": consumer() cannot be combined with startSeq(); set
   the start and the filter on the consumer "JOBS_ARCHIVE" instead
consumer() with startTime(), filterSubject():
   refused: Stream source "JOBS": consumer() cannot be combined with startTime(),
   filterSubject(); set the start and the filter on the consumer "JOBS_ARCHIVE" instead
an empty consumer name:
   refused: A stream source consumer needs a name
an empty deliver subject:
   refused: A stream source consumer needs a deliver subject

The message names the setters that clash and the consumer they belong on. An empty consumer name or deliver subject fails when consumer() is called, not later.

What the server takes without an error

The release notes warn that the server checks neither the consumer's name nor its deliver subject when the sourcing stream is created. pitfalls.php shows what that looks like, and what the server does refuse:

php
<?php
// pitfalls.php: what the server takes without an error, and what it refuses.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\Configuration\ConsumerConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;
use IDCT\NATS\JetStream\Enum\RetentionPolicy;

use function Amp\delay;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14514');
$js = $client->jetStream();

$jobs = function () use ($js): void {
    dropStreams($js, 'ARCHIVE', 'JOBS');
    $js->addStream(StreamConfiguration::create('JOBS')
        ->subjects('jobs.>')
        ->retention(RetentionPolicy::WorkQueue))->await();
};
$flowControl = fn(string $name, string $deliver): ConsumerConfiguration =>
    ConsumerConfiguration::create()
        ->durable($name)
        ->deliverSubject($deliver)
        ->ackPolicy(AckPolicy::FlowControl);
$archive = function (string $consumer, string $deliver) use ($js): void {
    $source = StreamSource::source('JOBS')->consumer($consumer, $deliver);
    $js->createStream('ARCHIVE', [], ['sources' => [$source->toArray()]])->await();
    echo "   ARCHIVE created, no error\n";
};
$publish = function () use ($js): void {
    foreach ([1, 2, 3] as $id) {
        $js->publish('jobs.email', "job-$id")->await();
    }
};
$try = function (string $label, callable $call): void {
    try {
        $call();
        echo "   $label: accepted\n";
    } catch (JetStreamException $e) {
        line("   $label: " . describe($e));
    }
};

echo "1. The source names another deliver subject than the consumer's:\n";
$jobs();
$js->addConsumer('JOBS', $flowControl('JOBS_ARCHIVE', 'deliver.jobs.archive'))->await();
$archive('JOBS_ARCHIVE', 'deliver.jobs.typo');
$publish();
delay(10);
printf("   10 s later: ARCHIVE %d | JOBS %d left\n", messages($js, 'ARCHIVE'),
    messages($js, 'JOBS'));

echo "2. The source names a consumer that does not exist yet:\n";
$jobs();
$archive('JOBS_LATE', 'deliver.jobs.late');
$publish();
delay(5);
printf("   5 s later: ARCHIVE %d | JOBS %d left\n", messages($js, 'ARCHIVE'),
    messages($js, 'JOBS'));
$js->addConsumer('JOBS', $flowControl('JOBS_LATE', 'deliver.jobs.late'))->await();
$started = microtime(true);
$count = waitFor($js, 'ARCHIVE', 3, 120);
printf("   then the consumer is created: ARCHIVE %d, %.0f s after that\n", $count,
    microtime(true) - $started);

echo "3. A flow_control consumer the server refuses:\n";
$jobs();
$try('with ackWait()', fn() => $js->addConsumer('JOBS',
    $flowControl('A', 'deliver.a')->ackWait(30_000))->await());
$try('with maxDeliver(5)', fn() => $js->addConsumer('JOBS',
    $flowControl('B', 'deliver.b')->maxDeliver(5))->await());
$try('delivering to jobs.archive', fn() => $js->addConsumer('JOBS',
    $flowControl('C', 'jobs.archive'))->await());

echo "4. A worker next to the archive consumer on the work queue:\n";
$js->addConsumer('JOBS', $flowControl('JOBS_ARCHIVE', 'deliver.jobs.archive'))->await();
$try('pull consumer WORKER', fn() => $js->addConsumer('JOBS',
    ConsumerConfiguration::create()->durable('WORKER')->ackPolicy(AckPolicy::Explicit))
    ->await());

$client->disconnect()->await();
text
Connected to nats-2-14, nats-server 2.14.10
1. The source names another deliver subject than the consumer's:
   ARCHIVE created, no error
   10 s later: ARCHIVE 0 | JOBS 3 left
2. The source names a consumer that does not exist yet:
   ARCHIVE created, no error
   5 s later: ARCHIVE 0 | JOBS 3 left
   then the consumer is created: ARCHIVE 3, 35 s after that
3. A flow_control consumer the server refuses:
   with ackWait(): 400, err_code 10221: flow control ack policy requires unset ack
     wait
   with maxDeliver(5): 400, err_code 10222: flow control ack policy requires unset max
     deliver
   delivering to jobs.archive: 400, err_code 10081: consumer deliver subject forms a
     cycle
4. A worker next to the archive consumer on the work queue:
   pull consumer WORKER: 400, err_code 10099: multiple non-filtered consumers not
     allowed on workqueue stream
  • A typo in the deliver subject fails silently. The archive was created, stayed empty for ten seconds, and the jobs stayed in the work queue. Nothing in the replies points at the cause, so keep the subject in one variable and pass it to both calls.
  • A consumer created after the stream is picked up, but not at once. In both of our runs it took 35 seconds. The README of 2.35.0 says "seconds or tens of seconds". Create the consumer first and there is no wait.
  • The server enforces the consumer's shape. An ack wait, a positive max_deliver and a deliver subject inside the origin's own subjects are refused, the last one as a cycle.
  • A work queue takes one unfiltered consumer. Once JOBS_ARCHIVE exists, a worker consumer on the same work queue is refused, because a WorkQueue stream does not allow overlapping consumers.

Workers next to the archive

So a work queue that is copied by a consumer of your own cannot also be worked off by another consumer. ADR-60 points to Interest or Limits retention for that case. With Interest, a message stays until every consumer has acknowledged it, the archive consumer included:

php
<?php
// interest.php: workers and an archive on the same origin, with Interest retention.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\JetStream\Configuration\ConsumerConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;
use IDCT\NATS\JetStream\Enum\RetentionPolicy;

use function Amp\delay;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14514');
$js = $client->jetStream();
dropStreams($js, 'ARCHIVE', 'TASKS');

$js->addStream(StreamConfiguration::create('TASKS')
    ->subjects('tasks.>')
    ->retention(RetentionPolicy::Interest))->await();
$js->addConsumer('TASKS', ConsumerConfiguration::create()
    ->durable('TASKS_ARCHIVE')
    ->deliverSubject('deliver.tasks.archive')
    ->ackPolicy(AckPolicy::FlowControl))->await();
$js->addConsumer('TASKS', ConsumerConfiguration::create()
    ->durable('WORKER')
    ->ackPolicy(AckPolicy::Explicit))->await();
$source = StreamSource::source('TASKS')
    ->consumer('TASKS_ARCHIVE', 'deliver.tasks.archive');
$js->createStream('ARCHIVE', [], ['sources' => [$source->toArray()]])->await();
echo "TASKS has two consumers: TASKS_ARCHIVE and WORKER\n";

$state = function (string $when) use ($js): void {
    printf("%sARCHIVE: %s | TASKS: %d left\n", $when, payloads($js, 'ARCHIVE'),
        messages($js, 'TASKS'));
};
foreach ([1, 2, 3] as $id) {
    $js->publish('tasks.resize', "task-$id")->await();
}
waitFor($js, 'ARCHIVE', 3);
delay(2);
$state('Archived, worker not done: ');

foreach ($js->fetchBatch('TASKS', 'WORKER', 10, 1000)->await() as $message) {
    $js->ackSync($message)->await();
}
delay(1);
$state('Worker acked all three:    ');

$client->disconnect()->await();
text
Connected to nats-2-14, nats-server 2.14.10
TASKS has two consumers: TASKS_ARCHIVE and WORKER
Archived, worker not done: ARCHIVE: task-1 task-2 task-3 | TASKS: 3 left
Worker acked all three:    ARCHIVE: task-1 task-2 task-3 | TASKS: 0 left

The three tasks were in the archive and still in TASKS while the worker had not acknowledged them. After the worker's acks, TASKS was empty. A message leaves only when both the archive and the worker have it.

Servers before 2.14

older.php creates the consumer and then a source that names it, and reports what the server stored. On a server that refuses the source, it falls back to the plain StreamSource::source():

php
<?php
// older.php: what a server before 2.14 answers; the client does not check the version.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\Configuration\ConsumerConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamConfiguration;
use IDCT\NATS\JetStream\Configuration\StreamSource;
use IDCT\NATS\JetStream\Enum\AckPolicy;
use IDCT\NATS\JetStream\Enum\RetentionPolicy;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14512');
$js = $client->jetStream();
dropStreams($js, 'ARCHIVE', 'JOBS');
$js->addStream(StreamConfiguration::create('JOBS')
    ->subjects('jobs.>')
    ->retention(RetentionPolicy::WorkQueue))->await();

echo "1. A consumer with AckPolicy::FlowControl:\n";
try {
    $js->addConsumer('JOBS', ConsumerConfiguration::create()
        ->durable('JOBS_ARCHIVE')
        ->deliverSubject('deliver.jobs.archive')
        ->ackPolicy(AckPolicy::FlowControl))->await();
    echo "   created\n";
} catch (JetStreamException $e) {
    line('   refused: ' . describe($e));
}

echo "2. A source that names the consumer:\n";
$named = StreamSource::source('JOBS')->consumer('JOBS_ARCHIVE', 'deliver.jobs.archive');
try {
    $sources = ['sources' => [$named->toArray()]];
    $info = $js->createStream('ARCHIVE', [], $sources)->await();
    $stored = $info->raw['config']['sources'][0];
    line('   created, stored source: ' . json($stored));
    echo isset($stored['consumer'])
        ? "   the consumer is in the stored config: durable sourcing\n"
        : "   no consumer in the stored config: the server sources the old way\n";
} catch (JetStreamException $e) {
    line('   refused: ' . describe($e));
    echo "3. The same source without consumer():\n";
    $plain = StreamSource::source('JOBS');
    $js->createStream('ARCHIVE', [], ['sources' => [$plain->toArray()]])->await();
    echo "   created\n";
}

echo "Three jobs, then the consumers on JOBS:\n";
foreach ([1, 2, 3] as $id) {
    $js->publish('jobs.email', "job-$id")->await();
}
waitFor($js, 'ARCHIVE', 3);
\Amp\delay(2);
printf("   ARCHIVE: %s | JOBS: %d left\n", payloads($js, 'ARCHIVE'),
    messages($js, 'JOBS'));
$consumers = $js->listConsumers('JOBS')->await();
if ($consumers === []) {
    echo "   no consumer listed on JOBS\n";
}
foreach ($consumers as $consumer) {
    $config = $consumer->raw['config'];
    printf("   %s, ack_policy %s, durable %s\n", $consumer->name, $config['ack_policy'],
        isset($config['durable_name']) ? 'yes' : 'no');
}

$client->disconnect()->await();

nats-server 2.10.29:

text
Connected to nats-2-10, nats-server 2.10.29
1. A consumer with AckPolicy::FlowControl:
   refused: 400, err_code 10025: invalid JSON
2. A source that names the consumer:
   created, stored source: {"name": "JOBS"}
   no consumer in the stored config: the server sources the old way
Three jobs, then the consumers on JOBS:
   ARCHIVE: job-1 job-2 job-3 | JOBS: 0 left
   no consumer listed on JOBS

nats-server 2.11.17:

text
Connected to nats-2-11, nats-server 2.11.17
1. A consumer with AckPolicy::FlowControl:
   refused: 400, err_code 10025: invalid JSON: can not unmarshal "\"flow_control\""
2. A source that names the consumer:
   created, stored source: {"name": "JOBS"}
   no consumer in the stored config: the server sources the old way
Three jobs, then the consumers on JOBS:
   ARCHIVE: job-1 job-2 job-3 | JOBS: 0 left
   no consumer listed on JOBS

nats-server 2.12.15:

text
Connected to nats-2-12, nats-server 2.12.15
1. A consumer with AckPolicy::FlowControl:
   refused: 400, err_code 10025: invalid JSON: can not unmarshal "\"flow_control\""
2. A source that names the consumer:
   refused: 400, err_code 10025: invalid JSON: json: unknown field "consumer"
3. The same source without consumer():
   created
Three jobs, then the consumers on JOBS:
   ARCHIVE: job-1 job-2 job-3 | JOBS: 0 left
   no consumer listed on JOBS

nats-server 2.14.10:

text
Connected to nats-2-14, nats-server 2.14.10
1. A consumer with AckPolicy::FlowControl:
   created
2. A source that names the consumer:
   created, stored source: {"name": "JOBS", "consumer": {"name": "JOBS_ARCHIVE",
     "deliver_subject": "deliver.jobs.archive"}}
   the consumer is in the stored config: durable sourcing
Three jobs, then the consumers on JOBS:
   ARCHIVE: job-1 job-2 job-3 | JOBS: 0 left
   JOBS_ARCHIVE, ack_policy flow_control, durable yes
  • 2.10 and 2.11 accept the source and drop the consumer. The stream is created without an error, and only the stored config shows that the consumer field is gone. That is the check the release recommends: look for consumer in raw['config']['sources'] of the StreamInfo that createStream() returns.
  • 2.12 refuses both, with err_code 10025 and a message that names the unknown field.
  • The old way copies a work queue too, on the same server. On all three older servers the archive got the jobs and the work queue was emptied, through a consumer that does not show up in the consumer list. What it does not have is the acknowledgement after storing: a message lost on the way is lost for good. We did not provoke that on the older servers.

Quality gates

From the release notes: PHPStan level 8; 4213 unit tests (with data sets) on PHP 8.2 to 8.5; 51 Behat scenarios and all 47 runnable examples pass. CI now runs the live integration suite twice: 175 tests against the nats-server 2.12 fixture stack, where 7 skip because they need 2.14, and 173 against nats-server 2.14, where nothing may skip (#279). Every changed line is covered (27 of 27), and total coverage is 99.12%. Infection reports a covered MSI of 92.69% against a 90% floor, with a caveat the release states itself: it skipped 5149 of the 9472 mutants it generated as too slow, so the score does not include them.

The 13 new unit cases for the two builders all fail on 2.34.0. The new live class DurableSourcingIntegrationTest ran its sourcing test against nats-server 2.14 in CI and its refusal test against 2.12. For the release, the README example and the live class were also checked against the official binaries of 2.10.29, 2.11.17, 2.12.15, 2.14.10 and 2.15.3.

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.