Repository navigation
Expand file tree
/
Copy pathObjectStoreBucketTest.php
More file actions
3893 lines (3331 loc) · 185 KB
/
Copy pathObjectStoreBucketTest.php
File metadata and controls
3893 lines (3331 loc) · 185 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\Unit;
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\ObjectStore\ObjectData;
use IDCT\NATS\JetStream\ObjectStore\ObjectInfo;
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreBucket;
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreWatchOptions;
use IDCT\NATS\Tests\Support\FakeTransport;
use PHPUnit\Framework\TestCase;
final class ObjectStoreBucketTest extends TestCase
{
/** URL-safe base64 (with padding), matching the official Object Store meta-subject encoding. */
private function encodeName(string $name): string
{
return strtr(base64_encode($name), '+/', '-_');
}
private function digestOf(string $data): string
{
return 'SHA-256=' . strtr(base64_encode(hash('sha256', $data, true)), '+/', '-_');
}
/** @param array<string,mixed> $extra */
private function metaGetResponse(string $name, array $extra): string
{
$meta = array_merge([
'name' => $name,
'bucket' => 'assets',
'mtime' => '2030-01-01T00:00:00Z',
'deleted' => false,
], $extra);
return (string) json_encode([
'message' => [
'subject' => '$O.assets.M.' . $this->encodeName($name),
'seq' => 2,
'data' => base64_encode((string) json_encode($meta, JSON_THROW_ON_ERROR)),
],
], JSON_THROW_ON_ERROR);
}
private function notFound(): string
{
return '{"error":{"code":404,"description":"message not found"}}';
}
/**
* Builds a Direct Get reply (HMSG) whose body is the raw meta JSON, as list() now reads it.
*
* @param array<string,mixed> $extra
*/
private function directMetaReply(string $name, array $extra, int $sid): string
{
$meta = array_merge([
'name' => $name,
'bucket' => 'assets',
'mtime' => '2030-01-01T00:00:00Z',
'deleted' => false,
], $extra);
$body = (string) json_encode($meta, JSON_THROW_ON_ERROR);
$hdrs = "NATS/1.0\r\nNats-Stream: OBJ_assets\r\nNats-Subject: \$O.assets.M." . $this->encodeName($name) . "\r\nNats-Sequence: 2\r\n\r\n";
$h = strlen($hdrs);
return sprintf("HMSG _INBOX.x %d %d %d\r\n%s%s\r\n", $sid, $h, $h + strlen($body), $hdrs, $body);
}
/** Builds a Direct Get reply (HMSG) for a single object chunk (raw bytes body on the NUID subject). */
private function directChunkReply(string $nuid, string $payload, int $sid): string
{
$hdrs = "NATS/1.0\r\nNats-Stream: OBJ_assets\r\nNats-Subject: \$O.assets.C.{$nuid}\r\nNats-Sequence: 3\r\n\r\n";
$h = strlen($hdrs);
return sprintf("HMSG _INBOX.x %d %d %d\r\n%s%s\r\n", $sid, $h, $h + strlen($payload), $hdrs, $payload);
}
/**
* Converts a metaGetResponse() STREAM.MSG.GET envelope into the equivalent Direct Get reply
* (HMSG with the raw meta JSON as the body), as info()/get()/getToCallback() now read it.
*/
private function directReplyFromEnvelope(string $envelope, int $sid): string
{
/** @var array{message: array{seq?: int, data?: string}} $decoded */
$decoded = json_decode($envelope, true, 512, JSON_THROW_ON_ERROR);
$metaJson = (string) base64_decode((string) ($decoded['message']['data'] ?? ''), true);
$seq = (int) ($decoded['message']['seq'] ?? 1);
$hdrs = "NATS/1.0\r\nNats-Stream: OBJ_assets\r\nNats-Sequence: {$seq}\r\n\r\n";
$h = strlen($hdrs);
return sprintf("HMSG _INBOX.x %d %d %d\r\n%s%s\r\n", $sid, $h, $h + strlen($metaJson), $hdrs, $metaJson);
}
/** Builds a Direct Get status-only reply (HMSG) such as a 404 miss or a non-404 error. */
private function directStatusReply(int $sid, int $code, string $description): string
{
$hdrs = "NATS/1.0 {$code} {$description}\r\nStatus: {$code}\r\nDescription: {$description}\r\n\r\n";
$h = strlen($hdrs);
return sprintf("HMSG _INBOX.x %d %d %d\r\n%s\r\n", $sid, $h, $h, $hdrs);
}
private function pubAck(int $seq): string
{
return sprintf('{"stream":"OBJ_assets","seq":%d,"duplicate":false}', $seq);
}
/**
* Post-#118 the request inbox is MUXED: request()/requestWithHeaders() no longer subscribe a fresh
* inbox per call; instead ONE long-lived wildcard "<base>.*" (sid 1) serves every reply, and each
* request publishes reply-to "<base>.<token>" and routes by that token. A pre-seeded fixed-subject
* "MSG/HMSG _INBOX.x <sid>" therefore no longer reaches the waiting request and it times out.
*
* Every Object Store operation that awaits a reply - JS publish acks (put/putStream chunk+meta),
* Direct Get (info/get/list per-subject), STREAM.INFO/PURGE/CREATE/DELETE, CONSUMER.CREATE/DELETE -
* funnels through request(), so their replies are mux replies. This installs a dynamic responder
* that learns the mux base from the wildcard SUB and, for each request PUB/HPUB (a publish whose
* reply-to lives under that base), pops the next reply frame FIFO and re-emits it on the CAPTURED
* reply-to with the mux sid (1). Frames are delivered in the order requests are written, matching
* the request/SID order the tests already encoded.
*
* Only request replies belong here; subscription deliveries (a pull fetch inbox, a batched Direct
* Get inbox, a watch push-consumer deliver subject) are NOT mux replies - enqueue those on their SUB
* via FakeTransport::$enqueueOnWriteContaining so they arrive with the sid the server assigned.
*
* @param list<string> $frames Pre-built MSG/HMSG reply frames; only their subject+sid are rewritten.
*/
private function muxReplies(FakeTransport $transport, array $frames): void
{
$queue = $frames;
$base = null;
$transport->onWrite = static function (string $bytes) use (&$queue, &$base): array {
$head = strtok($bytes, "\r\n");
if ($head === false) {
return [];
}
if (str_starts_with($head, 'SUB ')) {
// Learn the mux base from the wildcard registration "SUB <base>.* <sid>".
$subject = explode(' ', $head)[1] ?? '';
if (str_starts_with($subject, '_INBOX.') && str_ends_with($subject, '.*')) {
$base = substr($subject, 0, -1); // strip the trailing "*" -> "_INBOX.<hex>."
}
return [];
}
if ($base === null || (!str_starts_with($head, 'PUB ') && !str_starts_with($head, 'HPUB '))) {
return [];
}
// PUB <subject> <replyTo> <len> | HPUB <subject> <replyTo> <hdrLen> <totLen>
$replyTo = explode(' ', $head)[2] ?? '';
if (!str_starts_with($replyTo, $base) || $queue === []) {
// A plain publish, or a subscription's own inbox (fetch/direct-get) - not a mux request.
return [];
}
return [self::rewriteReplyFrame(array_shift($queue), $replyTo)];
};
}
/**
* Rewrites a pre-built MSG/HMSG reply frame's subject and sid to the request's captured mux reply-to
* and the mux sid (1), preserving the payload/header bytes and declared lengths verbatim so the
* reply's content is delivered unchanged - only its addressing is corrected for the mux inbox.
*/
private static function rewriteReplyFrame(string $frame, string $replyTo): string
{
$pos = strpos($frame, "\r\n");
self::assertNotFalse($pos, 'reply frame must have a head line');
$tokens = explode(' ', substr($frame, 0, $pos));
$tokens[1] = $replyTo; // subject
$tokens[2] = '1'; // mux sid
return implode(' ', $tokens) . substr($frame, $pos);
}
/**
* Verifies Object Store bucket create maps to a stream with chunk+meta subjects and rollup.
*/
public function testBucketCreateAndDelete(): void
{
$createPayload = '{"config":{"name":"OBJ_assets","subjects":["$O.assets.C.>","$O.assets.M.>"]}}';
$deletePayload = '{"success":true}';
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($createPayload), $createPayload),
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($deletePayload), $deletePayload),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$bucket = $client->jetStream()->objectStore('assets');
$created = $bucket->create()->await();
$deleted = $bucket->deleteBucket()->await();
self::assertSame('OBJ_assets', $created->name);
self::assertTrue($deleted);
self::assertStringContainsString('$JS.API.STREAM.CREATE.OBJ_assets', $transport->writes[3]);
self::assertStringContainsString('"allow_rollup_hdrs":true', $transport->writes[3]);
// Post-#118 the mux inbox has one shared "SUB <base>.* 1" and NO per-request UNSUB, so the
// second request's PUB is writes[4] (was writes[6] under the per-request SUB+UNSUB scheme).
self::assertStringContainsString('$JS.API.STREAM.DELETE.OBJ_assets', $transport->writes[4]);
}
/**
* Verifies put writes chunks under a NUID subject and rollup meta under the encoded name subject.
*/
public function testPutUsesEncodedMetaSubjectAndNuidChunks(): void
{
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// 1) existing-object lookup -> not found
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
// 2) chunk publish ack
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->pubAck(1)), $this->pubAck(1)),
// 3) meta publish ack
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen($this->pubAck(2)), $this->pubAck(2)),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$stored = $client->jetStream()->objectStore('assets')
->put('logo.txt', 'hello', ['content-type' => 'text/plain'])->await();
self::assertInstanceOf(ObjectInfo::class, $stored);
self::assertSame('logo.txt', $stored->name);
self::assertSame(5, $stored->size);
self::assertSame(1, $stored->chunks);
self::assertNotSame('', $stored->nuid);
self::assertSame($this->digestOf('hello'), $stored->digest);
$writes = implode('||', $transport->writes);
self::assertStringContainsString('PUB $O.assets.C.' . $stored->nuid . ' ', $writes);
self::assertStringContainsString('HPUB $O.assets.M.' . $this->encodeName('logo.txt') . ' ', $writes);
self::assertStringContainsString('Nats-Rollup:sub', $writes);
}
public function testPutOmitsEmptyMetadataSoOfficialClientsCanRead(): void
{
// #109: empty metadata must NOT serialize as a JSON array ("metadata":[]). The official Go client
// unmarshals metadata into map[string]string and rejects an array with
// "object-store meta information invalid"; it omits the field when empty. Match that so an object
// stored with default metadata stays readable by the nats CLI / nats.go.
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->pubAck(1)), $this->pubAck(1)),
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen($this->pubAck(2)), $this->pubAck(2)),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$client->jetStream()->objectStore('assets')->put('logo.txt', 'hello')->await();
$writes = implode('||', $transport->writes);
self::assertStringContainsString('HPUB $O.assets.M.' . $this->encodeName('logo.txt') . ' ', $writes);
self::assertStringNotContainsString('"metadata":[]', $writes);
// Omitted entirely when empty, exactly like the official client.
self::assertStringNotContainsString('"metadata":', $writes);
}
public function testPutSerializesNonEmptyMetadataAsJsonObject(): void
{
// #109: a populated metadata map must serialize as a JSON object so other clients can read it.
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->pubAck(1)), $this->pubAck(1)),
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen($this->pubAck(2)), $this->pubAck(2)),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$client->jetStream()->objectStore('assets')->put('logo.txt', 'hello', ['team' => 'brand'])->await();
$writes = implode('||', $transport->writes);
self::assertStringContainsString('"metadata":{"team":"brand"}', $writes);
}
public function testPutStreamReChunksAndComputesDigestIncrementally(): void
{
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
// lookup (concurrent), two chunk acks, meta ack - all mux request replies, FIFO by write order.
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->pubAck(1)), $this->pubAck(1)),
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen($this->pubAck(2)), $this->pubAck(2)),
sprintf("MSG _INBOX.d 4 %d\r\n%s\r\n", strlen($this->pubAck(3)), $this->pubAck(3)),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
// 3-byte chunks: a single 'hello' block re-chunks to 'hel' + 'lo' (2 chunks).
$store = new ObjectStoreBucket($client, $client->jetStream(), 'assets', 3);
$blocks = ['hello'];
$index = 0;
$stored = $store->putStream('big.txt', static function () use (&$index, $blocks): ?string {
return $blocks[$index++] ?? null;
})->await();
self::assertSame(5, $stored->size);
self::assertSame(2, $stored->chunks);
self::assertSame($this->digestOf('hello'), $stored->digest);
$writes = implode('||', $transport->writes);
self::assertSame(2, substr_count($writes, 'PUB $O.assets.C.' . $stored->nuid . ' '));
self::assertStringContainsString('HPUB $O.assets.M.' . $this->encodeName('big.txt'), $writes);
}
public function testPutStreamReChunksLargeBlockAcrossManyChunks(): void
{
// A single producer block larger than chunkSize must split into multiple chunks via the
// offset loop (no O(n^2) tail recopy), preserving order and digest.
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()), // lookup
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->pubAck(1)), $this->pubAck(1)), // chunk1
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen($this->pubAck(2)), $this->pubAck(2)), // chunk2
sprintf("MSG _INBOX.d 4 %d\r\n%s\r\n", strlen($this->pubAck(3)), $this->pubAck(3)), // chunk3
sprintf("MSG _INBOX.e 5 %d\r\n%s\r\n", strlen($this->pubAck(4)), $this->pubAck(4)), // meta
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
// 2-byte chunks: one 'abcdef' block re-chunks to 'ab' + 'cd' + 'ef' (3 chunks).
$store = new ObjectStoreBucket($client, $client->jetStream(), 'assets', 2);
$blocks = ['abcdef'];
$index = 0;
$stored = $store->putStream('big.bin', static function () use (&$index, $blocks): ?string {
return $blocks[$index++] ?? null;
})->await();
self::assertSame(6, $stored->size);
self::assertSame(3, $stored->chunks);
self::assertSame($this->digestOf('abcdef'), $stored->digest);
self::assertSame(3, substr_count(implode('||', $transport->writes), 'PUB $O.assets.C.' . $stored->nuid . ' '));
}
public function testConstructorRejectsNonPositiveChunkSize(): void
{
$client = new NatsClient(new NatsOptions(), new FakeTransport());
$this->expectException(JetStreamException::class);
$this->expectExceptionMessage('chunk size');
new ObjectStoreBucket($client, $client->jetStream(), 'assets', 0);
}
/**
* Verifies an empty object stores zero chunks and publishes no chunk message (only meta).
*/
public function testPutStoresEmptyObjectWithZeroChunks(): void
{
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
// With no chunk to await first, the meta publish is issued before the concurrent lookup, so
// the mux replies arrive meta-ack first, then the not-found lookup (FIFO by write order).
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->pubAck(1)), $this->pubAck(1)),
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$stored = $client->jetStream()->objectStore('assets')->put('empty.txt', '')->await();
self::assertSame(0, $stored->size);
self::assertSame(0, $stored->chunks);
$writes = implode('||', $transport->writes);
// No chunk was published for the empty object; only the meta record.
self::assertStringNotContainsString('PUB $O.assets.C.', $writes);
self::assertStringContainsString('HPUB $O.assets.M.' . $this->encodeName('empty.txt') . ' ', $writes);
}
/**
* Verifies an overwrite purges the previous revision's chunk subject.
*/
public function testPutOverwritePurgesPreviousChunks(): void
{
$oldNuid = 'oldnuid0001';
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// 1) existing-object lookup -> returns previous meta with old nuid
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->metaGetResponse('logo.txt', ['nuid' => $oldNuid, 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('old')])), $this->metaGetResponse('logo.txt', ['nuid' => $oldNuid, 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('old')])),
// 2) chunk publish ack
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->pubAck(3)), $this->pubAck(3)),
// 3) meta publish ack
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen($this->pubAck(4)), $this->pubAck(4)),
// 4) purge old chunks ack
sprintf("MSG _INBOX.d 4 %d\r\n%s\r\n", strlen('{"success":true,"purged":1}'), '{"success":true,"purged":1}'),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$client->jetStream()->objectStore('assets')->put('logo.txt', 'world')->await();
$writes = implode('||', $transport->writes);
self::assertStringContainsString('$JS.API.STREAM.PURGE.OBJ_assets', $writes);
self::assertStringContainsString('$O.assets.C.' . $oldNuid, $writes);
}
/**
* Verifies get downloads chunks via NUID subject and verifies the content digest.
*/
public function testGetReturnsPayloadAndVerifiesDigest(): void
{
$nuid = 'nuidget0001';
$meta = $this->metaGetResponse('doc.txt', [
'nuid' => $nuid,
'size' => 5,
'chunks' => 1,
'digest' => $this->digestOf('hello'),
]);
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
$this->directReplyFromEnvelope($meta, 1), // info() (Direct Get)
$this->directChunkReply($nuid, 'hello', 2), // single-chunk fast path (Direct Get on the NUID subject)
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$fetched = $client->jetStream()->objectStore('assets')->get('doc.txt')->await();
self::assertInstanceOf(ObjectData::class, $fetched);
self::assertSame('hello', $fetched->data);
self::assertSame('doc.txt', $fetched->info->name);
self::assertSame($nuid, $fetched->info->nuid);
// The single chunk is fetched via Direct Get on its NUID subject (no ephemeral consumer).
$writes = implode('||', $transport->writes);
self::assertStringContainsString('"last_by_subj":"$O.assets.C.' . $nuid . '"', $writes);
self::assertStringNotContainsString('CONSUMER.CREATE', $writes);
}
public function testGetVerifiesUnpaddedBase64UrlDigest(): void
{
$nuid = 'nuidunpad01';
// A non-Go client may store the digest as UNPADDED base64url; byte comparison must still
// verify it against our padded computation instead of throwing a spurious mismatch.
$unpadded = rtrim($this->digestOf('hello'), '=');
self::assertNotSame($unpadded, $this->digestOf('hello')); // guard: the fixture is actually unpadded
$meta = $this->metaGetResponse('doc.txt', ['nuid' => $nuid, 'size' => 5, 'chunks' => 1, 'digest' => $unpadded]);
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
$this->directReplyFromEnvelope($meta, 1),
$this->directChunkReply($nuid, 'hello', 2),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$fetched = $client->jetStream()->objectStore('assets')->get('doc.txt')->await();
self::assertInstanceOf(ObjectData::class, $fetched);
self::assertSame('hello', $fetched->data);
}
/**
* Verifies get throws on a content digest mismatch.
*/
public function testGetThrowsOnDigestMismatch(): void
{
$nuid = 'nuidbad0001';
$meta = $this->metaGetResponse('doc.txt', [
'nuid' => $nuid,
'size' => 11,
'chunks' => 1,
'digest' => $this->digestOf('hello world'),
]);
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
$this->directReplyFromEnvelope($meta, 1),
$this->directChunkReply($nuid, 'CORRUPTED!!', 2), // body does not match the metadata digest
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$this->expectException(JetStreamException::class);
$this->expectExceptionMessage('Object digest mismatch');
$client->jetStream()->objectStore('assets')->get('doc.txt')->await();
}
/**
* Verifies getToCallback invokes the callback exactly once for a single-chunk object and
* streams that chunk's payload to the handler. (Multi-chunk per-chunk streaming is proven by
* testGetToCallbackInvokesCallbackOncePerChunk.)
*/
public function testGetToCallbackInvokesCallbackOnceForSingleChunkObject(): void
{
$nuid = 'nuidcb00001';
$meta = $this->metaGetResponse('report.txt', [
'nuid' => $nuid,
'size' => 5,
'chunks' => 1,
'digest' => $this->digestOf('hello'),
]);
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
$this->directReplyFromEnvelope($meta, 1),
$this->directChunkReply($nuid, 'hello', 2),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$captured = '';
$calls = 0;
$info = $client->jetStream()->objectStore('assets')->getToCallback(
'report.txt',
static function (string $chunk) use (&$captured, &$calls): void {
$captured .= $chunk;
$calls++;
},
)->await();
self::assertSame('hello', $captured);
self::assertSame(1, $calls);
self::assertNotNull($info);
self::assertSame('report.txt', $info->name);
}
/**
* Verifies getToCallback invokes the callback once per stored chunk (in order) for a multi-chunk
* object, rather than buffering the whole object and calling back once.
*/
public function testGetToCallbackInvokesCallbackOncePerChunk(): void
{
$nuid = 'nuidcbmulti';
$chunks = ['abc', 'def', 'ghi'];
$assembled = implode('', $chunks);
$meta = $this->metaGetResponse('multi.txt', [
'nuid' => $nuid,
'size' => strlen($assembled),
'chunks' => count($chunks),
'digest' => $this->digestOf($assembled),
]);
$consumer = '{"stream_name":"OBJ_assets","name":"EPHCBM","config":{"ack_policy":"explicit"}}';
$deleteConsumer = '{"success":true}';
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
// The three chunks arrive on the pull fetch inbox (sid 2: mux SUB=1, ephemeral consumer create
// is a mux request, fetch SUB=2), not on the mux request inbox - enqueue on the fetch SUB.
$transport->enqueueOnWriteContaining = [
'_INBOX.JS.FETCH' => [
"MSG _INBOX.JS.FETCH.c 2 3\r\nabc\r\n",
"MSG _INBOX.JS.FETCH.c 2 3\r\ndef\r\n",
"MSG _INBOX.JS.FETCH.c 2 3\r\nghi\r\n",
],
];
$this->muxReplies($transport, [
$this->directReplyFromEnvelope($meta, 1), // info() Direct Get
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($consumer), $consumer), // CONSUMER.CREATE
sprintf("MSG _INBOX.d 4 %d\r\n%s\r\n", strlen($deleteConsumer), $deleteConsumer), // CONSUMER.DELETE
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$captured = [];
$info = $client->jetStream()->objectStore('assets')->getToCallback(
'multi.txt',
static function (string $chunk) use (&$captured): void {
$captured[] = $chunk;
},
)->await();
// One invocation per stored chunk, in order - the whole object is never assembled.
self::assertSame(['abc', 'def', 'ghi'], $captured);
self::assertNotNull($info);
self::assertSame('multi.txt', $info->name);
self::assertSame(3, $info->chunks);
}
/**
* Verifies getToCallback returns null for a deleted object without invoking the callback.
*/
public function testGetToCallbackReturnsNullForDeletedObjects(): void
{
$meta = $this->metaGetResponse('gone.txt', ['nuid' => '', 'size' => 0, 'chunks' => 0, 'digest' => '', 'deleted' => true]);
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
$this->directReplyFromEnvelope($meta, 1),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$called = false;
$info = $client->jetStream()->objectStore('assets')->getToCallback(
'gone.txt',
static function (string $chunk) use (&$called): void {
$called = true;
},
)->await();
self::assertFalse($called);
// A deleted object reads as not-available; the tombstone stays visible via info().
self::assertNull($info);
}
/**
* Verifies delete writes a tombstone via the encoded meta subject and purges chunks.
*/
public function testDeleteWritesTombstoneAndPurgesChunks(): void
{
$oldNuid = 'delnuid0001';
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
// The tombstone publish is issued before the concurrent lookup (no chunk to await first), then
// the purge; mux replies arrive in that write order.
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->pubAck(7)), $this->pubAck(7)),
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->metaGetResponse('logo.txt', ['nuid' => $oldNuid, 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('old')])), $this->metaGetResponse('logo.txt', ['nuid' => $oldNuid, 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('old')])),
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen('{"success":true,"purged":1}'), '{"success":true,"purged":1}'),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$deleted = $client->jetStream()->objectStore('assets')->delete('logo.txt')->await();
self::assertTrue($deleted->deleted);
$writes = implode('||', $transport->writes);
self::assertStringContainsString('HPUB $O.assets.M.' . $this->encodeName('logo.txt') . ' ', $writes);
self::assertStringContainsString('$JS.API.STREAM.PURGE.OBJ_assets', $writes);
self::assertStringContainsString('$O.assets.C.' . $oldNuid, $writes);
}
/**
* Verifies put() stores a description and surfaces it on ObjectInfo (#58).
*/
public function testPutWithDescription(): void
{
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()), // lookupExisting -> none
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($this->pubAck(1)), $this->pubAck(1)), // chunk publish ack
sprintf("MSG _INBOX.c 3 %d\r\n%s\r\n", strlen($this->pubAck(2)), $this->pubAck(2)), // meta publish ack
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$info = $client->jetStream()->objectStore('assets')->put('doc.txt', 'hello', [], 'A friendly doc')->await();
self::assertSame('A friendly doc', $info->description);
$writes = implode('||', $transport->writes);
self::assertStringContainsString('"description":"A friendly doc"', $writes);
$client->disconnect()->await();
}
/**
* Verifies get() transparently follows an object link to the target's content (#59).
*/
public function testGetFollowsObjectLink(): void
{
$nuid = 'nuidlink001';
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// info('shortcut') -> link meta pointing at doc.txt (Direct Get).
$this->directMetaReply('shortcut', ['options' => ['link' => ['bucket' => 'assets', 'name' => 'doc.txt']]], 1),
// info('doc.txt') -> the real object meta.
$this->directMetaReply('doc.txt', ['nuid' => $nuid, 'size' => 5, 'chunks' => 1, 'digest' => $this->digestOf('hello')], 2),
// single-chunk Direct Get on the target NUID subject.
$this->directChunkReply($nuid, 'hello', 3),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$fetched = $client->jetStream()->objectStore('assets')->get('shortcut')->await();
self::assertInstanceOf(ObjectData::class, $fetched);
self::assertSame('hello', $fetched->data);
self::assertSame('doc.txt', $fetched->info->name);
$client->disconnect()->await();
}
/**
* Verifies create() accepts a typed ObjectStoreConfig and maps it to stream config (#39).
*/
public function testCreateWithTypedConfig(): void
{
$reply = '{"config":{"name":"OBJ_assets"}}';
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($reply), $reply),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$client->jetStream()->objectStore('assets')->create(
new \IDCT\NATS\JetStream\ObjectStore\ObjectStoreConfig(ttlSeconds: 60, maxBytes: 4096, storage: 'memory', replicas: 3, compression: 's2'),
)->await();
$create = $transport->writes[3];
self::assertStringContainsString('$JS.API.STREAM.CREATE.OBJ_assets', $create);
self::assertStringContainsString('"max_age":60000000000', $create);
self::assertStringContainsString('"max_bytes":4096', $create);
self::assertStringContainsString('"storage":"memory"', $create);
self::assertStringContainsString('"num_replicas":3', $create);
self::assertStringContainsString('"compression":"s2"', $create);
}
/**
* Verifies seal() updates the backing stream with sealed=true, preserving existing config (#38).
*/
public function testSeal(): void
{
$info = '{"config":{"name":"OBJ_assets","subjects":["$O.assets.>"],"max_bytes":1000}}';
$updated = '{"config":{"name":"OBJ_assets","sealed":true}}';
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($info), $info), // STREAM.INFO
sprintf("MSG _INBOX.b 2 %d\r\n%s\r\n", strlen($updated), $updated), // STREAM.UPDATE
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
self::assertTrue($client->jetStream()->objectStore('assets')->seal()->await());
// seal() issues STREAM.INFO then STREAM.UPDATE; post-#118 (one shared mux SUB, no per-request
// UNSUB) the second request's PUB is writes[4] (was writes[6] under the old per-request scheme).
self::assertStringContainsString('$JS.API.STREAM.UPDATE.OBJ_assets', $transport->writes[4]);
self::assertStringContainsString('"sealed":true', $transport->writes[4]);
self::assertStringContainsString('"max_bytes":1000', $transport->writes[4]);
}
/**
* Verifies addLink() writes a link meta record pointing at a target object (#48).
*/
public function testAddLink(): void
{
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// Name-free check (STREAM.MSG.GET): no existing object under "shortcut".
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
// Target check (Direct Get): "real.bin" exists and is a live stored object.
$this->directMetaReply('real.bin', ['nuid' => 'n1', 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('abc')], 2),
sprintf("MSG _INBOX.b 3 %d\r\n%s\r\n", strlen($this->pubAck(3)), $this->pubAck(3)),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$link = $client->jetStream()->objectStore('assets')->addLink('shortcut', 'real.bin')->await();
self::assertTrue($link->isLink());
self::assertSame(['bucket' => 'assets', 'name' => 'real.bin'], $link->link);
$write = $transport->writes[5];
self::assertStringContainsString('HPUB $O.assets.M.' . $this->encodeName('shortcut') . ' ', $write);
self::assertStringContainsString('"link":{"bucket":"assets","name":"real.bin"}', $write);
}
/**
* addLink() must refuse to overwrite a LIVE object (nats.go ErrObjectAlreadyExists): the
* rollup meta publish would make the object's content unreachable in one call and orphan its
* chunks forever (no purge runs on the link path). Pre-fix this silently succeeded.
*/
public function testAddLinkRejectsExistingLiveObject(): void
{
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// "shortcut" already holds a live stored object (STREAM.MSG.GET envelope).
sprintf(
"MSG _INBOX.a 1 %d\r\n%s\r\n",
strlen($this->metaGetResponse('shortcut', ['nuid' => 'nLive', 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('abc')])),
$this->metaGetResponse('shortcut', ['nuid' => 'nLive', 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('abc')]),
),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
try {
$client->jetStream()->objectStore('assets')->addLink('shortcut', 'real.bin')->await();
self::fail('a link must not silently replace a live object');
} catch (JetStreamException $e) {
self::assertStringContainsString('already exists', $e->getMessage());
}
self::assertStringNotContainsString('HPUB $O.assets.M.', implode('', $transport->writes), 'no meta record may be written');
}
/**
* Re-pointing an existing LINK is allowed (nats.go parity: `if !einfo.isLink() { return
* ErrObjectAlreadyExists }`): a link stores no chunks, so nothing is orphaned - the standard
* "latest"-alias flow must keep working.
*/
public function testAddLinkAllowsRepointingAnExistingLink(): void
{
$existingLink = $this->metaGetResponse('latest', ['nuid' => '', 'options' => ['link' => ['bucket' => 'assets', 'name' => 'v1.bin']]]);
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// Name check: "latest" currently holds a LINK -> allowed to re-point.
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($existingLink), $existingLink),
// Target check: v2.bin is a live stored object.
$this->directMetaReply('v2.bin', ['nuid' => 'n2', 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('two')], 2),
sprintf("MSG _INBOX.b 3 %d\r\n%s\r\n", strlen($this->pubAck(9)), $this->pubAck(9)),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$link = $client->jetStream()->objectStore('assets')->addLink('latest', 'v2.bin')->await();
self::assertTrue($link->isLink());
self::assertSame(['bucket' => 'assets', 'name' => 'v2.bin'], $link->link);
}
/**
* A DELETED object's tombstone blocks addLink() exactly like a live object (nats.go parity:
* AddLink reads the info with ShowDeleted and returns ErrObjectAlreadyExists for any non-link
* record) - put -> delete -> addLink on the same name must throw, not create the link.
* Pre-fix the tombstone passed the guard, silently diverging from nats.go on shared buckets.
*/
public function testAddLinkRejectsDeletedTombstoneName(): void
{
$tombstone = $this->metaGetResponse('shortcut', ['nuid' => '', 'size' => 0, 'chunks' => 0, 'deleted' => true]);
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// Name check: "shortcut" holds a DELETED tombstone (STREAM.MSG.GET envelope).
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($tombstone), $tombstone),
// Only consumed by the PRE-FIX path (tombstone passes the guard): a live target and a
// publish ack would let the link complete, turning the missing rejection into a fail().
$this->directMetaReply('real.bin', ['nuid' => 'n1', 'size' => 3, 'chunks' => 1, 'digest' => $this->digestOf('abc')], 2),
sprintf("MSG _INBOX.b 3 %d\r\n%s\r\n", strlen($this->pubAck(4)), $this->pubAck(4)),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
try {
$client->jetStream()->objectStore('assets')->addLink('shortcut', 'real.bin')->await();
self::fail('a link over a deleted tombstone must be rejected (nats.go ErrObjectAlreadyExists)');
} catch (JetStreamException $e) {
// Pin the contract (the NAME is blocked with the already-exists error), not the exact
// phrasing - a message reword must not break this test (3rd-round review).
self::assertStringContainsString('shortcut', $e->getMessage());
self::assertStringContainsString('already exists', $e->getMessage());
}
self::assertStringNotContainsString('HPUB $O.assets.M.', implode('', $transport->writes), 'no link meta record may be written');
}
/**
* addLink() must reject a deleted (or absent) target and a target that is itself a link -
* both dangle by construction (nats.go parity).
*/
public function testAddLinkRejectsDeletedTargetAndLinkTarget(): void
{
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);
$this->muxReplies($transport, [
// Case 1: name free (STREAM.MSG.GET 404), target deleted (Direct Get).
sprintf("MSG _INBOX.a 1 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
$this->directMetaReply('gone.bin', ['nuid' => 'n1', 'deleted' => true], 2),
// Case 2: name free, target is itself a link.
sprintf("MSG _INBOX.b 3 %d\r\n%s\r\n", strlen($this->notFound()), $this->notFound()),
$this->directMetaReply('alias.bin', ['nuid' => '', 'options' => ['link' => ['bucket' => 'assets', 'name' => 'real.bin']]], 4),
]);
$client = new NatsClient(new NatsOptions(requestTimeoutMs: 1000), $transport);
$client->connect()->await();
$bucket = $client->jetStream()->objectStore('assets');
try {
$bucket->addLink('l1', 'gone.bin')->await();
self::fail('a link to a deleted target must be rejected');
} catch (JetStreamException $e) {
self::assertStringContainsString('deleted', $e->getMessage());
}
try {
$bucket->addLink('l2', 'alias.bin')->await();
self::fail('a link to another link must be rejected');
} catch (JetStreamException $e) {
self::assertStringContainsString('itself a link', $e->getMessage());
}
}
/**
* A no-responders reply to the meta-record rollup publish (publishMeta, reached by every
* put/link/updateMeta) must surface as JetStreamException(503) - the same taxonomy jsRequest()
* produces - not a bare NatsException, so a JetStream-disabled server / unbound subject is
* catchable as JetStreamException like every other JS path (#161).
*/
public function testMetaPublishNormalizesNoRespondersTo503(): void
{
$status = "NATS/1.0 503\r\n\r\n";
$transport = new FakeTransport([
'INFO {"server_id":"S1","server_name":"n1","version":"2.12.0","jetstream":true,"max_payload":1048576,"headers":true}' . "\r\n",
"PONG\r\n",
]);