Repository navigation
Expand file tree
/
Copy pathJetStreamIntegrationTest.php
More file actions
2236 lines (1800 loc) · 87.8 KB
/
Copy pathJetStreamIntegrationTest.php
File metadata and controls
2236 lines (1800 loc) · 87.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace IDCT\NATS\Tests\Integration;
use Amp\CancelledException;
use Amp\Future;
use Amp\TimeoutCancellation;
use IDCT\NATS\Connection\Enum\ConnectionState;
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Core\NatsHeaders;
use IDCT\NATS\Core\NatsMessage;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\KeyValue\KeyValueEntry;
use IDCT\NATS\JetStream\KeyValue\KeyWatchOptions;
use IDCT\NATS\JetStream\ObjectStore\ObjectData;
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreBucket;
use IDCT\NATS\Tests\Support\DroppingTransport;
use IDCT\NATS\Transport\AmpSocketTransport;
use PHPUnit\Framework\TestCase;
use function Amp\async;
use function Amp\delay;
final class JetStreamIntegrationTest extends TestCase
{
use IntegrationTestBootstrap;
/**
* Verifies account info and basic stream lifecycle operations against live JetStream.
*/
public function testJetStreamAccountAndStreamLifecycle(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$account = $js->accountInfo()->await();
$created = $js->createStream($stream, ['it.' . strtolower($stream) . '.>'])->await();
$fetched = $js->getStream($stream)->await();
$deleted = $js->deleteStream($stream)->await();
self::assertGreaterThanOrEqual(0, $account->streams);
self::assertSame($stream, $created->name);
self::assertSame($stream, $fetched->name);
self::assertTrue($deleted);
$client->disconnect()->await();
}
/**
* Verifies consumer lifecycle and publish acknowledgment against live JetStream.
*/
public function testJetStreamConsumerAndPublishAck(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.events';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$created = $js->createConsumer($stream, $consumer, $subject)->await();
$fetched = $js->getConsumer($stream, $consumer)->await();
$ack = $js->publish($subject, '{"event":"created"}')->await();
$deletedConsumer = $js->deleteConsumer($stream, $consumer)->await();
$deletedStream = $js->deleteStream($stream)->await();
self::assertSame($stream, $created->streamName);
self::assertSame($consumer, $fetched->name);
self::assertSame($stream, $ack->stream);
self::assertGreaterThanOrEqual(1, $ack->seq);
self::assertTrue($deletedConsumer);
self::assertTrue($deletedStream);
$client->disconnect()->await();
}
/**
* Verifies consumer list API returns durable consumers created for a stream.
*/
public function testJetStreamListConsumers(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.consumers';
$consumerA = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$consumerB = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$js->createConsumer($stream, $consumerA, $subject)->await();
$js->createConsumer($stream, $consumerB, $subject)->await();
$consumers = $js->listConsumers($stream)->await();
$names = array_map(static fn($consumer): string => $consumer->name, $consumers);
self::assertContains($consumerA, $names);
self::assertContains($consumerB, $names);
$js->deleteConsumer($stream, $consumerA)->await();
$js->deleteConsumer($stream, $consumerB)->await();
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies stream update persists modified subject configuration.
*/
public function testJetStreamUpdateStreamConfiguration(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subjectA = 'it.' . strtolower($stream) . '.a';
$subjectB = 'it.' . strtolower($stream) . '.b';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subjectA])->await();
$updated = $js->updateStream($stream, ['subjects' => [$subjectA, $subjectB]])->await();
$fetched = $js->getStream($stream)->await();
self::assertSame($stream, $updated->name);
self::assertContains($subjectA, $updated->subjects);
self::assertContains($subjectB, $updated->subjects);
self::assertContains($subjectA, $fetched->subjects);
self::assertContains($subjectB, $fetched->subjects);
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies a subject-filtered purge removes only the matching subject's messages and leaves the
* other subject's messages intact (a real filtered purge, not a whole-stream purge).
*/
public function testJetStreamPurgeStreamByFilter(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$prefix = 'it.' . strtolower($stream);
$purgeSubject = $prefix . '.purge';
$keepSubject = $prefix . '.keep';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$purgeSubject, $keepSubject])->await();
// Two messages on the subject we will purge, one on the subject we will keep.
$js->publish($purgeSubject, '{"event":"one"}')->await();
$js->publish($purgeSubject, '{"event":"two"}')->await();
$js->publish($keepSubject, '{"event":"keep"}')->await();
$stateBefore = $js->getStream($stream)->await()->raw['state'] ?? [];
self::assertSame(3, (int) ($stateBefore['messages'] ?? -1));
// Filtered purge: only the matching subject's messages are removed.
$purge = $js->purgeStream($stream, ['filter' => $purgeSubject])->await();
self::assertSame(2, $purge['purged']);
// Total count drops to exactly the kept subject's single message.
$stateAfter = $js->getStream($stream)->await()->raw['state'] ?? [];
self::assertSame(1, (int) ($stateAfter['messages'] ?? -1));
// The kept subject's message is still retrievable.
$kept = $js->getLastMessageForSubject($stream, $keepSubject)->await();
self::assertSame($keepSubject, $kept->subject);
self::assertSame('{"event":"keep"}', $kept->payload);
// The purged subject has no remaining messages: the leader reports a 404.
try {
$js->getLastMessageForSubject($stream, $purgeSubject)->await();
self::fail('Expected purged subject to have no remaining messages.');
} catch (JetStreamException $e) {
self::assertGreaterThanOrEqual(400, $e->getCode());
}
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies direct stream message get returns payload by sequence.
*/
public function testJetStreamGetStreamMessage(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.direct';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$ack = $js->publish($subject, '{"event":"direct-get"}')->await();
$message = $js->getStreamMessage($stream, $ack->seq)->await();
self::assertSame($subject, $message->subject);
self::assertSame('{"event":"direct-get"}', $message->payload);
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies getStreamMessage preserves a falsy "0" body and any stored headers.
*/
public function testJetStreamGetStreamMessagePreservesZeroAndHeaders(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.zh';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
// Same connection, so these publishes are processed before the getStreamMessage request
// below; no manual pump needed (getStreamMessage uses its own request/reply).
$zeroAck = $js->publish($subject, '0')->await();
$client->publishWithHeaders($subject, 'body', ['X-Custom' => 'present'])->await();
$zero = $js->getStreamMessage($stream, $zeroAck->seq)->await();
self::assertSame('0', $zero->payload);
$withHeaders = $js->getStreamMessage($stream, $zeroAck->seq + 1)->await();
self::assertNotNull($withHeaders->rawHeaders);
self::assertSame('present', NatsHeaders::fromWireBlock($withHeaders->rawHeaders)['X-Custom'] ?? null);
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies the Direct Get API ($JS.API.DIRECT.GET) on an allow_direct stream: fetch by sequence,
* fetch last-by-subject, and a missing-sequence error.
*/
public function testJetStreamDirectGetStreamMessage(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.dg';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject], ['allow_direct' => true])->await();
$ack = $js->publish($subject, '{"event":"direct"}')->await();
// Direct Get by sequence returns the raw body and carries the original subject.
$bySeq = $js->directGetStreamMessage($stream, $ack->seq)->await();
self::assertSame($subject, $bySeq->subject);
self::assertSame('{"event":"direct"}', $bySeq->payload);
// Direct Get last-by-subject returns the most recent message on the subject.
$js->publish($subject, 'newest')->await();
$last = $js->directGetLastMessageForSubject($stream, $subject)->await();
self::assertSame('newest', $last->payload);
// A missing sequence is reported as a JetStreamException, not an empty message.
try {
$js->directGetStreamMessage($stream, 99_999)->await();
self::fail('Expected JetStreamException for a missing sequence');
} catch (JetStreamException $e) {
self::assertGreaterThanOrEqual(400, $e->getCode());
}
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies that many request()/reply round-trips issued concurrently on one connection all
* resolve independently and quickly - the contract KV getAll() / ObjectStore list() rely on when
* they fan out Direct Get lookups. Guards against a regression in the self-pumping read machinery.
*/
public function testConcurrentRequestsAllResolve(): void
{
$this->requireIntegrationEnabled();
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$futures = [];
for ($i = 0; $i < 12; $i++) {
$futures[] = async(static fn(): NatsMessage => $client->request('$JS.API.INFO', '')->await());
}
/** @var list<NatsMessage> $results */
$results = Future\await($futures, new TimeoutCancellation(5.0));
self::assertCount(12, $results);
foreach ($results as $reply) {
self::assertNotSame('', $reply->payload);
}
$client->disconnect()->await();
}
/**
* Verifies a pipelined multi-chunk upload round-trips intact: a tiny chunk size forces many
* chunks across more than one in-flight window, and an exact-bytes + digest match on download
* proves the pipelined publishes preserved stream order.
*/
public function testJetStreamObjectStorePipelinedMultiChunkRoundTrip(): void
{
$this->requireIntegrationEnabled();
$bucket = 'mc' . strtolower(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
// 64-byte chunks over a ~2 KiB payload => ~32 chunks => more than one pipeline window.
$store = new ObjectStoreBucket($client, $client->jetStream(), $bucket, 64);
$store->create()->await();
$payload = bin2hex(random_bytes(1024)); // 2048 bytes
$info = $store->put('blob.bin', $payload)->await();
self::assertGreaterThan(16, $info->chunks);
$data = $store->get('blob.bin')->await();
self::assertNotNull($data);
// get() verifies the SHA-256 digest internally; an exact-bytes match additionally proves the
// pipelined chunks were stored and reassembled in order.
self::assertSame($payload, $data->data);
$store->deleteBucket()->await();
$client->disconnect()->await();
}
/**
* Verifies putStream() uploads from a producer callback (memory-bounded), re-chunking blocks of
* varying size, and round-trips intact (exact bytes + internal digest verification on download).
*/
public function testJetStreamObjectStorePutStreamRoundTrip(): void
{
$this->requireIntegrationEnabled();
$bucket = 'ps' . strtolower(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$store = new ObjectStoreBucket($client, $client->jetStream(), $bucket, 64);
$store->create()->await();
// Blocks of varying size (none aligned to the 64-byte chunk size) exercise re-chunking.
$blocks = [bin2hex(random_bytes(150)), bin2hex(random_bytes(200)), bin2hex(random_bytes(174))];
$expected = implode('', $blocks);
$index = 0;
$info = $store->putStream('stream.bin', static function () use (&$index, $blocks): ?string {
return $blocks[$index++] ?? null;
})->await();
self::assertSame(strlen($expected), $info->size);
self::assertGreaterThan(1, $info->chunks);
$data = $store->get('stream.bin')->await();
self::assertNotNull($data);
self::assertSame($expected, $data->data);
$store->deleteBucket()->await();
$client->disconnect()->await();
}
/**
* Verifies stream list API includes newly created streams.
*/
public function testJetStreamListStreams(): void
{
$this->requireIntegrationEnabled();
$streamA = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$streamB = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subjectA = 'it.' . strtolower($streamA) . '.list';
$subjectB = 'it.' . strtolower($streamB) . '.list';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($streamA, [$subjectA])->await();
$js->createStream($streamB, [$subjectB])->await();
$streams = $js->listStreams()->await();
$names = array_map(static fn($stream): string => $stream->name, $streams);
self::assertContains($streamA, $names);
self::assertContains($streamB, $names);
$js->deleteStream($streamA)->await();
$js->deleteStream($streamB)->await();
$client->disconnect()->await();
}
/**
* Verifies scheduled publish delivers a delayed message to the configured target subject.
*/
public function testJetStreamScheduledPublish(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$scheduleSubject = 'schedules.' . strtolower($stream) . '.one';
$targetSubject = 'events.' . strtolower($stream) . '.scheduled';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream(
$stream,
[$scheduleSubject, $targetSubject],
['allow_msg_schedules' => true],
)->await();
$ack = $js->publishScheduled(
$scheduleSubject,
$targetSubject,
'{"event":"scheduled"}',
'@at ' . gmdate('Y-m-d\TH:i:s\Z', time() + 2),
null,
)->await();
$observedMessages = 0;
$delivered = false;
$deadline = $this->monotonic() + 6.0;
while (!$delivered && $this->monotonic() < $deadline) {
$state = $js->getStream($stream)->await()->raw['state'] ?? [];
$observedMessages = max(0, (int) ($state['messages'] ?? 0));
$delivered = $observedMessages >= 1;
if ($delivered) {
continue;
}
delay(0.25);
}
self::assertSame($stream, $ack->stream);
self::assertGreaterThanOrEqual(1, $observedMessages);
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies scheduled publish with a per-message TTL works when the stream enables both
* allow_msg_schedules and allow_msg_ttl (the exact combination shown in the README example).
*/
public function testJetStreamScheduledPublishWithPerMessageTtl(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$scheduleSubject = 'schedules.' . strtolower($stream) . '.ttl';
$targetSubject = 'events.' . strtolower($stream) . '.ttl';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream(
$stream,
[$scheduleSubject, $targetSubject],
['allow_msg_schedules' => true, 'allow_msg_ttl' => true],
)->await();
$ack = $js->publishScheduled(
$scheduleSubject,
$targetSubject,
'{"event":"scheduled-ttl"}',
'@at ' . gmdate('Y-m-d\TH:i:s\Z', time() + 2),
'5m',
)->await();
self::assertSame($stream, $ack->stream);
self::assertGreaterThanOrEqual(1, $ack->seq);
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies unsupported schedule expressions are rejected before publish.
*/
public function testJetStreamScheduledPublishRejectsUnsupportedPatterns(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$scheduleSubject = 'schedules.' . strtolower($stream) . '.invalid';
$targetSubject = 'events.' . strtolower($stream) . '.invalid';
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream(
$stream,
[$scheduleSubject, $targetSubject],
['allow_msg_schedules' => true],
)->await();
try {
$js->publishScheduled(
$scheduleSubject,
$targetSubject,
'{"event":"bad-schedule"}',
'not-a-schedule',
null,
)->await();
self::fail('Expected unsupported schedule expression to be rejected.');
} catch (JetStreamException $e) {
// @at / @every / cron / predefined aliases are accepted; a malformed expression is rejected
// client-side before any round-trip.
self::assertStringContainsString('Unsupported schedule expression', $e->getMessage());
}
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies pull consumer fetch-next and explicit ACK workflow against live JetStream.
*/
public function testJetStreamPullFetchAndAck(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.pull';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$js->createConsumer($stream, $consumer, $subject)->await();
$published = $js->publish($subject, '{"event":"pull"}')->await();
self::assertSame($stream, $published->stream);
$message = $js->fetchNext($stream, $consumer, 4000)->await();
self::assertSame('{"event":"pull"}', $message->payload);
self::assertNotNull($message->replyTo);
$js->ack($message)->await();
$js->deleteConsumer($stream, $consumer)->await();
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies delayed NAK triggers redelivery for pull consumers.
*/
public function testJetStreamPullNakWithDelayRedelivery(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.pull.nak';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$js->createConsumer($stream, $consumer, $subject)->await();
$js->publish($subject, '{"event":"redeliver"}')->await();
$first = $js->fetchNext($stream, $consumer, 4000)->await();
self::assertSame('{"event":"redeliver"}', $first->payload);
$js->nakWithDelay($first, 1200)->await();
// The redelivery is due ~1.2s after the NAK. Poll for it, tolerating transient pull timeouts
// (408): a single fixed wait + one fetch is flaky because server-side redelivery timing can
// jitter past one pull window (#70). The overall deadline still fails fast if the message is
// genuinely never redelivered.
$second = null;
$deadline = $this->monotonic() + 15.0;
while ($second === null && $this->monotonic() < $deadline) {
try {
$second = $js->fetchNext($stream, $consumer, 2000)->await();
} catch (JetStreamException $e) {
if (!str_contains($e->getMessage(), '408')) {
throw $e;
}
// 408 Request Timeout: the redelivery has not arrived yet - pull again.
}
}
self::assertNotNull($second, 'NAK-with-delay message must be redelivered');
self::assertSame('{"event":"redeliver"}', $second->payload);
$js->ack($second)->await();
$js->deleteConsumer($stream, $consumer)->await();
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies TERM and WPI tokens influence pull-consumer redelivery workflow.
*/
public function testJetStreamTermAndInProgressTokens(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.pull.termwpi';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
// ack_wait 3s (not 1s): the WPI is sent ~0.6s after delivery and the no-redelivery probe
// takes up to ~0.5s more - under an xdebug-instrumented run the pre-WPI steps can eat a
// 1s window entirely, letting ack_wait expire and the server legitimately redeliver
// before the WPI lands (#70 family). 3s keeps every step well inside the window while the
// redelivery poll below still sees the post-WPI redelivery within its deadline.
$js->createConsumer($stream, $consumer, $subject, [
'ack_wait' => 3_000_000_000,
'max_deliver' => 3,
])->await();
// WPI should extend in-flight processing and delay redelivery.
$js->publish($subject, '{"event":"wpi"}')->await();
$first = $js->fetchNext($stream, $consumer, 4_000)->await();
self::assertSame('{"event":"wpi"}', $first->payload);
delay(0.6);
$js->inProgress($first)->await();
try {
$js->fetchBatch($stream, $consumer, 1, 500)->await();
self::fail('Expected no immediate redelivery after WPI heartbeat.');
} catch (JetStreamException $e) {
self::assertMatchesRegularExpression('/status (404|408)|No messages received within timeout/i', $e->getMessage());
}
// Generous deadline: redelivery is due ~ack_wait (3s) after the WPI, but the poll must tolerate
// server-timer jitter and a slow (xdebug-instrumented) run without flaking (#70 family).
$redelivered = null;
$deadline = $this->monotonic() + 12.0;
while ($redelivered === null && $this->monotonic() < $deadline) {
try {
$redelivered = $js->fetchNext($stream, $consumer, 800)->await();
} catch (JetStreamException $e) {
if (!preg_match('/status (404|408)|No messages received within timeout/i', $e->getMessage())) {
throw $e;
}
}
}
self::assertNotNull($redelivered);
self::assertSame('{"event":"wpi"}', $redelivered->payload);
$js->ack($redelivered)->await();
// TERM should stop further redeliveries for a message.
$js->publish($subject, '{"event":"term"}')->await();
$toTerm = $js->fetchNext($stream, $consumer, 4_000)->await();
self::assertSame('{"event":"term"}', $toTerm->payload);
$js->term($toTerm)->await();
delay(1.3);
try {
$js->fetchBatch($stream, $consumer, 1, 700)->await();
self::fail('Expected TERM-ed message to stop redelivery.');
} catch (JetStreamException $e) {
self::assertMatchesRegularExpression('/status (404|408)|No messages received within timeout/i', $e->getMessage());
}
$js->deleteConsumer($stream, $consumer)->await();
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies pull-consumer iterator batching processes messages across chained pulls.
*/
public function testJetStreamPullIteratorBatching(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.pull.iterator';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$js->createConsumer($stream, $consumer, $subject)->await();
for ($i = 1; $i <= 5; $i++) {
$js->publish($subject, json_encode(['n' => $i], JSON_THROW_ON_ERROR))->await();
}
$seen = [];
$total = $js->pullConsumer($stream, $consumer)
->setBatching(2)
->setExpiresMs(700)
->setIterations(4)
->handle(static function (NatsMessage $message, $context) use (&$seen): void {
$seen[] = $message->payload;
if ($message->replyTo !== null && $message->replyTo !== '') {
$context->ack($message)->await();
}
})->await();
sort($seen);
self::assertSame(5, $total);
self::assertSame([
'{"n":1}',
'{"n":2}',
'{"n":3}',
'{"n":4}',
'{"n":5}',
], $seen);
$js->deleteConsumer($stream, $consumer)->await();
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies an infinite consume loop with setMaxBytes() survives an oversized pending head
* message: the server answers the pull with a 409 "Message Size Exceeds MaxBytes" completion
* status, and the loop must keep (paced) pulling instead of stopping permanently, delivering
* a fitting message once the oversized one is removed (#153).
*/
public function testJetStreamInfiniteConsumeWithMaxBytesSurvivesOversizedPendingMessage(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.pull.maxbytes';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$js->createConsumer($stream, $consumer, $subject)->await();
// The head message exceeds the pull max_bytes cap by an order of magnitude.
$oversizedAck = $js->publish($subject, str_repeat('x', 4096))->await();
// Contract check: a direct capped fetch against the oversized head surfaces the 409
// completion status (this is the status the iterator must keep polling through).
try {
$js->fetchBatch($stream, $consumer, 1, 500, ['max_bytes' => 512])->await();
self::fail('Expected a 409 MaxBytes status for an oversized pending head message.');
} catch (JetStreamException $e) {
self::assertSame(409, $e->getCode());
self::assertStringContainsStringIgnoringCase('maxbytes', $e->getMessage());
}
$iter = $js->pullConsumer($stream, $consumer)
->setBatching(1)
->setExpiresMs(500)
->setMaxBytes(512)
->setIterations(null); // infinite
$received = [];
$future = $iter->handle(static function (NatsMessage $message, $context) use (&$received, $iter): void {
$received[] = $message->payload;
if ($message->replyTo !== null && $message->replyTo !== '') {
$context->ack($message)->await();
}
$iter->stop();
});
// Let the loop face the 409 window at least once, then clear the oversized head and
// publish a message that fits: a loop that (wrongly) stopped on the 409 never delivers it.
delay(0.25);
$js->deleteMessage($stream, $oversizedAck->seq)->await();
$js->publish($subject, '{"n":"fits"}')->await();
try {
$total = $future->await(new TimeoutCancellation(10));
} catch (CancelledException) {
$iter->stop();
self::fail('Infinite consume loop did not deliver the follow-up message after the MaxBytes 409 window.');
}
self::assertSame(1, $total);
self::assertSame(['{"n":"fits"}'], $received);
$js->deleteConsumer($stream, $consumer)->await();
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* Verifies durable push helper delivers live payloads to subscribed handlers.
*/
public function testJetStreamPushConsumerHelperDelivery(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.push';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$received = null;
$sid = $js->subscribePushConsumer(
$stream,
$consumer,
static function (NatsMessage $message) use (&$received, $js): void {
$received = $message;
$js->ack($message)->await();
},
null,
$subject,
)->await();
$js->publish($subject, '{"event":"push"}')->await();
$cancellation = new TimeoutCancellation(4.0);
try {
while ($received === null) {
$client->processIncoming($cancellation)->await();
}
} catch (CancelledException) {
}
self::assertInstanceOf(NatsMessage::class, $received);
self::assertSame('{"event":"push"}', $received->payload);
$client->unsubscribe($sid)->await();
$js->deleteConsumer($stream, $consumer)->await();
$js->deleteStream($stream)->await();
$client->disconnect()->await();
}
/**
* #150 - a REAL JetStream push consumer whose handler calls the JetStream ack path (`ack()`,
* which publishes `+ACK` to the message reply subject) while the connection is Draining. The
* server pushes a message that stays buffered on the subscriber's socket (no pump before drain),
* so drain()'s own flush-phase read delivers it during Draining; the handler's ack must reach the
* wire even though the connection is no longer Open, the subscriber must end Closed, and the ack
* must be recorded server-side (num_ack_pending and num_pending both drain to 0), confirming the
* delivered message was durably acknowledged rather than left for redelivery.
*/
public function testDrainDeliversJetStreamPushConsumerAckToTheServer(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.drainack';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
// Admin connection creates the stream/consumer and later verifies the ack server-side.
$admin = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$admin->connect()->await();
$adminJs = $admin->jetStream();
$adminJs->createStream($stream, [$subject])->await();
// Subscriber runs the push consumer; disable heartbeats so no background self-read consumes
// the pushed message before drain()'s flush-phase read does.
$subscriber = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()], pingIntervalSeconds: 0));
$subscriber->connect()->await();
$js = $subscriber->jetStream();
$handled = false;
$ackError = null;
$ackState = null;
$js->subscribePushConsumer(
$stream,
$consumer,
static function (NatsMessage $message) use (&$handled, &$ackError, &$ackState, $js, $subscriber): void {
$handled = true;
$ackState = $subscriber->state();
try {
// The real JetStream ack path; it must reach the wire while state is Draining.
$js->ack($message)->await();
} catch (\Throwable $e) {
$ackError = $e;
}
},
null,
$subject,
)->await();
// Register the consumer interest server-side before publishing.
$subscriber->flush()->await();
// Publish one message, then do NOT pump: the server's push MSG stays buffered on the socket
// until drain()'s flush-phase read consumes and delivers it during Draining.
$adminJs->publish($subject, '{"event":"drain-ack"}')->await();
delay(0.3);
$subscriber->drain()->await();
self::assertTrue($handled, 'the push message must be delivered to the handler during drain');
self::assertSame(ConnectionState::Draining, $ackState, 'the ack must run while the connection is Draining');
self::assertNull($ackError, 'the JetStream ack must not throw while the connection is Draining');
self::assertSame(ConnectionState::Closed, $subscriber->state());
// Server-side: the delivered message must be acknowledged (nothing left to ack, nothing left
// pending), proving the ack sent during drain was durably recorded rather than lost.
$deadline = $this->monotonic() + 5.0;
$info = $adminJs->getConsumer($stream, $consumer)->await();
while (
((int) ($info->raw['num_ack_pending'] ?? -1) !== 0 || (int) ($info->raw['num_pending'] ?? -1) !== 0)
&& $this->monotonic() < $deadline
) {
delay(0.1);
$info = $adminJs->getConsumer($stream, $consumer)->await();
}
self::assertSame(0, (int) ($info->raw['num_ack_pending'] ?? -1), 'the ack sent during drain must be recorded server-side');
self::assertSame(0, (int) ($info->raw['num_pending'] ?? -1), 'the delivered message must not be left pending for redelivery');
$adminJs->deleteConsumer($stream, $consumer)->await();
$adminJs->deleteStream($stream)->await();
$admin->disconnect()->await();
}
/**
* Verifies durable push helper works with an explicit deliver subject.
*/
public function testJetStreamPushConsumerWithExplicitDeliverSubject(): void
{
$this->requireIntegrationEnabled();
$stream = 'IT_' . strtoupper(bin2hex(random_bytes(3)));
$subject = 'it.' . strtolower($stream) . '.push.explicit';
$deliver = 'deliver.' . strtolower($stream) . '.events';
$consumer = 'C_' . strtoupper(bin2hex(random_bytes(2)));
$client = new NatsClient(new NatsOptions(servers: [$this->integrationServerUrl()]));
$client->connect()->await();
$js = $client->jetStream();
$js->createStream($stream, [$subject])->await();
$received = null;
$sid = $js->subscribePushConsumer(
$stream,
$consumer,
static function (NatsMessage $message) use (&$received, $js): void {
$received = $message;
$js->ack($message)->await();
},
$deliver,
$subject,
)->await();
$js->publish($subject, '{"event":"push-explicit"}')->await();
$cancellation = new TimeoutCancellation(4.0);
try {