-
Notifications
You must be signed in to change notification settings - Fork 4
/
jet_stream.tcl
1284 lines (1222 loc) · 50.4 KB
/
jet_stream.tcl
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
# Copyright (c) 2021-2023 Petro Kazmirchuk https://github.com/Kazmirchuk
# Copyright (c) 2021 ANT Solutions https://antsolutions.eu/
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
# JetStream wire API Reference https://docs.nats.io/reference/reference-protocols/nats_api_reference
# JetStream JSON API Design https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-1.md
oo::class create ::nats::SyncPullRequest {
variable Conn MsgList Status ID
constructor {} {
set MsgList [list]
set Status running ;# one of: running, done, timeout
}
method run {conn subject msg timeout batch } {
set Conn $conn
set ID [$conn request $subject $msg -dictmsg true -timeout $timeout -max_msgs $batch -callback [nats::mymethod OnMsg]]
try {
while {1} {
nats::_coroVwait [self namespace]::Status ;# wait for 1 message
set msgCount [llength $MsgList]
switch -- $Status {
timeout {
# check if the connection is lost/closed.
# It could have been still possible to return messages received so far, but the user wouldn't be able to ACK them anyway,
# so we discard them
set connNs [info object namespace $Conn]
if {[set ${connNs}::status] eq $nats::status_closed} {
if {[set ${connNs}::last_error] eq ""} {
throw {NATS ErrConnectionClosed} "Connection closed"
}
throw {NATS ErrTimeout} "Connection lost"
}
if {$msgCount > 0} {
break ;# we've received at least some messages - return them
}
# it might seem strange to throw ErrTimeout only in this case
# but it is consistent with nats.go, see func TestPullSubscribeFetchWithHeartbeat
throw {NATS ErrTimeout} "Sync pull request timeout, subject=$subject"
}
done {
# we've received a status message, which means that the pull request is done
if {$batch - $msgCount > 1} {
# no need to cancel the request if this was the last expected message
$Conn cancel_request $ID
}
break
}
default {
if {$msgCount == $batch} {
break
}
}
}
}
return $MsgList
} finally {
my destroy
}
}
method OnMsg {timedOut msg} {
if {$timedOut} {
# client-side timeout or connection lost; we may have received some messages before
[info object namespace $Conn]::log::debug "Sync pull request $ID timed out"
set Status timeout
return
}
set msgStatus [nats::header lookup $msg Status ""]
switch -- $msgStatus {
100 {
return
}
404 - 408 - 409 {
[info object namespace $Conn]::log::debug "Sync pull request $ID got status message $msgStatus"
set Status done
}
default {
lappend MsgList $msg
set Status running
}
}
}
}
oo::class create ::nats::AsyncPullRequest {
variable Conn Batch UserCb MsgCount ID
constructor {cb} {
set UserCb $cb
set MsgCount 0 ;# only user's messages
set ID 0
}
method run {conn subject msg timeout batch} {
set Conn $conn
set Batch $batch
set ID [$conn request $subject $msg -dictmsg true -timeout $timeout -max_msgs $batch -callback [nats::mymethod OnMsg]]
return [self]
}
method OnMsg {timedOut msg} {
if {$timedOut} {
# client-side timeout or connection lost; we may have received some messages before
[info object namespace $Conn]::log::debug "Async pull request $ID timed out"
set invokeCb 1
set connNs [info object namespace $Conn]
if {[set ${connNs}::status] eq $nats::status_closed} {
if {[set ${connNs}::last_error] eq ""} {
set invokeCb 0 ;# same as async requests
}
}
if {$invokeCb} {
after 0 [list {*}$UserCb 1 ""]
}
set ID 0 ;# the request has been already cancelled by OldStyleRequest
my destroy
return
}
set msgStatus [nats::header lookup $msg Status ""]
switch -- $msgStatus {
100 {
return
}
404 - 408 - 409 {
[info object namespace $Conn]::log::debug "Async pull request $ID got status message $msgStatus"
after 0 [list {*}$UserCb 1 $msg] ;# just like with old-style requests, inform the user that the pull request timed out
my destroy
}
default {
incr MsgCount
after 0 [list {*}$UserCb 0 $msg]
if {$MsgCount == $Batch} {
my destroy
}
}
}
}
destructor {
if {$Batch - $MsgCount <= 1 || $ID == 0} {
return
}
$Conn cancel_request $ID
}
}
oo::class create ::nats::jet_stream {
variable Conn Timeout ApiPrefix Domain Trace ChildrenRef
constructor {conn timeout api_prefix domain trace} {
set Conn $conn
set Timeout $timeout
set Trace $trace
array set ChildrenRef {}
if {$api_prefix ne ""} {
set ApiPrefix $api_prefix
return
}
set Domain $domain
if {$domain eq ""} {
set ApiPrefix "\$JS.API"
} else {
set ApiPrefix "\$JS.$domain.API"
}
}
destructor {
$Conn releaseRef [self]
foreach obj [array names ChildrenRef] {
$obj destroy
}
}
# internal
method addRef {obj} {
set ChildrenRef($obj) ""
}
method releaseRef {obj} {
unset -nocomplain ChildrenRef($obj)
}
method api_prefix {} {
return $ApiPrefix
}
method timeout {} {
return $Timeout
}
# JetStream Direct Get https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-31.md
method stream_direct_get {stream args} {
set spec {last_by_subj valid_str null
next_by_subj valid_str null
seq int null}
nats::_parse_args $args $spec
if [info exists last_by_subj] {
set reqSubj "$ApiPrefix.DIRECT.GET.$stream.$last_by_subj"
set reqMsg ""
} else {
set reqSubj "$ApiPrefix.DIRECT.GET.$stream"
set reqMsg [nats::_local2json $spec]
}
# ApiRequest assumes that the reply is always JSON which is not the case for DIRECT.GET
if {$Trace} {
[info object namespace $Conn]::log::debug ">>> $reqSubj $reqMsg"
}
set msg [$Conn request $reqSubj $reqMsg -timeout $Timeout -dictmsg 1]
if {$Trace} {
[info object namespace $Conn]::log::debug "<<< $reqSubj $msg"
}
set status [nats::header lookup $msg Status 0]
switch -- $status {
404 {
throw {NATS ErrMsgNotFound} "no message found"
}
408 {
throw {NATS ErrInvalidArg} "Invalid request"
}
}
dict set msg seq [nats::header get $msg Nats-Sequence]
dict set msg time [nats::header get $msg Nats-Time-Stamp]
dict set msg subject [nats::header get $msg Nats-Subject]
foreach h {Nats-Sequence Nats-Time-Stamp Nats-Subject Nats-Stream} {
nats::header delete msg $h
}
return $msg
}
# nats schema info --yaml io.nats.jetstream.api.v1.stream_msg_get_request
# nats schema info --yaml io.nats.jetstream.api.v1.stream_msg_get_response
# https://docs.nats.io/reference/reference-protocols/nats_api_reference#fetching-from-a-stream-by-sequence
method stream_msg_get {stream args} {
set spec {last_by_subj valid_str null
next_by_subj valid_str null
seq int null}
set response [my ApiRequest "STREAM.MSG.GET.$stream" [nats::_dict2json $spec $args]]
set encoded_msg [dict get $response message]
set data [binary decode base64 [dict lookup $encoded_msg data]]
if {[$Conn cget -utf8_convert]} {
# ofc method MSG has "convertfrom" as well, but it has no effect on base64 data, so we need to call "convertfrom" again
set data [encoding convertfrom utf-8 $data]
}
set msg [nats::msg create [dict get $encoded_msg subject] -data $data]
dict set msg seq [dict get $encoded_msg seq]
dict set msg time [dict get $encoded_msg time]
set header [binary decode base64 [dict lookup $encoded_msg hdrs]]
if {$header ne ""} {
dict set msg header [nats::_parse_header $header]
}
return $msg
}
# nats schema info --yaml io.nats.jetstream.api.v1.stream_msg_delete_request
# nats schema info --yaml io.nats.jetstream.api.v1.stream_msg_delete_response
method stream_msg_delete {stream args} {
set spec {no_erase bool true
seq int NATS_TCL_REQUIRED}
set response [my ApiRequest "STREAM.MSG.DELETE.$stream" [nats::_dict2json $spec $args]]
return [dict get $response success]
}
# for backwards compatibility; do not confuse with the new "consume" algorithm from JetStream client API 2.0
method consume {args} {
return [my fetch {*}$args]
}
# Pull Subscribe internals https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-13.md
# JetStream Subscribe Workflow https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-15.md
# nats schema info --yaml io.nats.jetstream.api.v1.consumer_getnext_request
method fetch {stream consumer args} {
if {![my CheckFilenameSafe $stream]} {
throw {NATS ErrInvalidArg} "Invalid stream name $stream"
}
if {![my CheckFilenameSafe $consumer]} {
throw {NATS ErrInvalidArg} "Invalid consumer name $consumer"
}
set subject "$ApiPrefix.CONSUMER.MSG.NEXT.$stream.$consumer"
nats::_parse_args $args {
timeout timeout null
batch_size pos_int 1
expires timeout null
callback valid_str ""
}
# timeout specifies the client-side timeout; if not given, this is a no_wait fetch
# expires specifies the server-side timeout (undocumented option only for testing)
if {[info exists timeout]} {
set no_wait false
if {![info exists expires]} {
set expires [expr {$timeout >= 20 ? $timeout - 10 : $timeout}] ;# same as in nats.go v1, see func (sub *Subscription) Fetch
# but in JS v2 they've changed default expires to 30s
}
} else {
if {[info exists expires]} {
throw {NATS ErrInvalidArg} "-expires requires -timeout"
}
set no_wait true
set timeout $Timeout
}
# implementation in official clients is overly complex and is done in 2 steps:
# 1. a no_wait fetch
# 2. followed by a long fetch
# and they have a special optimized case for batch=1.
# I don't see a need for such intricacies in this client
set json_spec {
expires ns null
batch int null
no_wait bool null
}
set batch $batch_size
# if there are no messages at all, and I send a no_wait request, I get back 404
# if there are no messages, and I send no_wait=false, I get 408 after the request expires
# if there are some messages, I get them followed by 408
# if there are all needed messages, there's no additional status message
# both classes self-destruct, when the pull request is done
if {$callback eq ""} {
set req [nats::SyncPullRequest new]
} else {
set req [nats::AsyncPullRequest new $callback]
}
set msg [nats::_local2json $json_spec]
if {$Trace} {
[info object namespace $Conn]::log::debug ">>> $subject $msg"
}
try {
return [$req run $Conn $subject $msg $timeout $batch]
} trap {NATS ErrTimeout} {err errOpts} {
if {$err ne "Connection lost"} {
# only for sync fetches:
# probably wrong stream/consumer - see also https://github.com/nats-io/nats-server/issues/2107
# raise a more meaningful ErrConsumerNotFound/ErrStreamNotFound/ErrJetStreamNotEnabled
my consumer_info $stream $consumer
}
# if consumer_info doesn't throw, rethrow the original error
return -options $errOpts $err
}
}
method cancel_pull_request {fetchID} {
if {![info object isa object $fetchID]} {
throw {NATS ErrInvalidArg} "Invalid fetch ID $fetchID"
}
$fetchID destroy
}
# different types of ACKs: https://docs.nats.io/using-nats/developer/develop_jetstream/consumers#delivery-reliability
method ack {message} {
$Conn publish [nats::msg reply $message] ""
}
method ack_sync {message} {
$Conn request [nats::msg reply $message] "" -timeout $Timeout
}
method nak {message args} {
nats::_parse_args $args {
delay timeout null
}
set nack_msg "-NAK"
if {[info exists delay]} {
append nack_msg " [nats::_local2json {delay ns null}]"
}
$Conn publish [nats::msg reply $message] $nack_msg
}
method term {message} {
$Conn publish [nats::msg reply $message] "+TERM"
}
method in_progress {message} {
$Conn publish [nats::msg reply $message] "+WPI"
}
# nats schema info --yaml io.nats.jetstream.api.v1.pub_ack_response
method publish {subject message args} {
set msg [nats::msg create $subject -data $message]
return [my publish_msg $msg {*}$args]
}
method publish_msg {msg args} {
nats::_parse_args $args {
timeout timeout null
callback valid_str ""
stream valid_str ""
}
if {![info exists timeout]} {
set timeout $Timeout
}
if {$stream ne ""} {
nats::header set msg Nats-Expected-Stream $stream
}
if {$callback ne ""} {
return [$Conn request_msg $msg -callback [nats::mymethod PublishCallback $callback] -timeout $timeout -dictmsg false]
}
set response [json::json2dict [$Conn request_msg $msg -timeout $timeout -dictmsg false]]
nats::_checkJsError $response
return $response ;# fields: stream,seq,duplicate
}
method add_consumer {stream args} {
my AddUpdateConsumer $stream create {*}$args
}
method update_consumer {stream args} {
my AddUpdateConsumer $stream update {*}$args
}
# nats schema info --yaml io.nats.jetstream.api.v1.consumer_create_request
# nats schema info --yaml io.nats.jetstream.api.v1.consumer_create_response
method AddUpdateConsumer {stream action args} {
set spec {name valid_str null
durable_name valid_str null
description valid_str null
deliver_policy {enum all last new by_start_sequence by_start_time last_per_subject} all
opt_start_seq int null
opt_start_time valid_str null
ack_policy {enum none all explicit} explicit
ack_wait ns null
max_deliver int null
filter_subject valid_str null
replay_policy {enum instant original} instant
rate_limit_bps int null
sample_freq valid_str null
max_waiting int null
max_ack_pending int null
flow_control bool null
idle_heartbeat ns null
headers_only bool null
deliver_subject valid_str null
deliver_group valid_str null
inactive_threshold ns null
num_replicas int null
mem_storage bool null
metadata metadata null}
nats::_parse_args $args $spec
if {[info exists name]} {
if {![my CheckFilenameSafe $name]} {
throw {NATS ErrInvalidArg} "Invalid consumer name $name"
}
if {[info exists durable_name]} {
throw {NATS ErrInvalidArg} "-name conflicts with -durable_name"
}
}
# see JetStreamManager.add_consumer in nats.py
set version_cmp [package vcompare 2.9 [dict get [$Conn server_info] version]]
set check_subj true
if {($version_cmp < 1) && [info exists name]} {
if {[info exists filter_subject] && $filter_subject ne ">"} {
set subject "CONSUMER.CREATE.$stream.$name.$filter_subject"
set check_subj false ;# if filter_subject has * or >, it can't pass the check in CheckSubject
} else {
set subject "CONSUMER.CREATE.$stream.$name"
}
} elseif {[info exists durable_name]} {
set subject "CONSUMER.DURABLE.CREATE.$stream.$durable_name"
} else {
set subject "CONSUMER.CREATE.$stream"
}
set jsonDict [dict create stream_name [json::write string $stream] config [nats::_local2json $spec]]
set version_cmp [package vcompare 2.10 [dict get [$Conn server_info] version]]
if {$version_cmp < 1} {
# seems like older NATS servers ignore "action", but let's be safe and send it only if NATS version >= 2.10
dict set jsonDict action [json::write string $action]
}
set response [my ApiRequest $subject [json::write object {*}$jsonDict] $check_subj]
set result_config [dict get $response config]
nats::_ns2ms result_config ack_wait idle_heartbeat inactive_threshold
dict set response config $result_config
return $response
}
method add_pull_consumer {stream consumer args} {
set config $args
dict set config durable_name $consumer
return [my add_consumer $stream {*}$config]
}
method add_push_consumer {stream consumer deliver_subject args} {
dict set args durable_name $consumer
dict set args deliver_subject $deliver_subject
return [my add_consumer $stream {*}$args]
}
method add_consumer_from_json {stream consumer json_config} {
set msg [json::write object stream_name [json::write string $stream] config $json_config]
set json_response [$Conn request "$ApiPrefix.CONSUMER.DURABLE.CREATE.$stream.$consumer" $msg -timeout $Timeout -dictmsg false]
set dict_response [json::json2dict $json_response]
nats::_checkJsError $dict_response
return $json_response
}
# no request body
# nats schema info --yaml io.nats.jetstream.api.v1.consumer_delete_response
method delete_consumer {stream consumer} {
set response [my ApiRequest "CONSUMER.DELETE.$stream.$consumer" ""]
return [dict get $response success] ;# probably will always be true
}
# nats schema info --yaml io.nats.jetstream.api.v1.consumer_info_response
method consumer_info {stream consumer} {
set response [my ApiRequest "CONSUMER.INFO.$stream.$consumer" ""]
# response fields: name, stream_name, created, config and some others
set result_config [dict get $response config]
nats::_ns2ms result_config ack_wait idle_heartbeat inactive_threshold
dict set response config $result_config
return $response
}
# nats schema info --yaml io.nats.jetstream.api.v1.consumer_names_request
# the schema suggests possibility to filter by subject, but it doesn't work!
# nats schema info --yaml io.nats.jetstream.api.v1.consumer_names_response
method consumer_names {stream} {
set response [my ApiRequest "CONSUMER.NAMES.$stream" ""]
return [dict get $response consumers]
}
method ordered_consumer {stream args} {
if {![my CheckFilenameSafe $stream]} {
throw {NATS ErrInvalidArg} "Invalid stream name $stream"
}
set spec {callback valid_str ""
description valid_str null
headers_only bool null
deliver_policy str null
idle_heartbeat ns 5000
filter_subject valid_str null
post bool true}
nats::_parse_args $args $spec
set consumerConfig [nats::_local2dict $spec]
# remove the args that do not belong to a consumer configuration
dict unset consumerConfig callback
dict unset consumerConfig post
set ordConsumer [nats::ordered_consumer new $Conn [self] $stream $consumerConfig $callback $post]
if {$post} {
# if $post=false, the consumer is owned by a KV watcher
set ChildrenRef($ordConsumer) ""
}
return $ordConsumer
}
method add_stream {stream args} {
return [my AddUpdateStream $stream CREATE {*}$args]
}
method update_stream {stream args} {
return [my AddUpdateStream $stream UPDATE {*}$args]
}
# nats schema info --yaml io.nats.jetstream.api.v1.stream_create_request
# nats schema info --yaml io.nats.jetstream.api.v1.stream_create_response
# nats schema info --yaml io.nats.jetstream.api.v1.stream_update_response
method AddUpdateStream {stream action args} {
if {![my CheckFilenameSafe $stream]} {
throw {NATS ErrInvalidArg} "Invalid stream name $stream"
}
# follow the same order of fields as in nats.go/jetstream/stream_config.go
set spec {
name valid_str null
description valid_str null
subjects list null
retention {enum limits interest workqueue} limits
max_consumers int null
max_msgs int null
max_bytes int null
discard {enum new old} null
max_age ns null
max_msgs_per_subject int null
max_msg_size int null
storage {enum memory file} file
num_replicas int null
no_ack bool null
duplicate_window ns null
mirror json null
sources json_list null
sealed bool null
deny_delete bool null
deny_purge bool null
allow_rollup_hdrs bool null
compression {enum none s2} null
first_seq int null
subject_transform json null
republish json null
allow_direct bool null
mirror_direct bool null
metadata metadata null}
dict set args name $stream ;# required by NATS despite having it already in the subject
# -subjects is normally also required unless we have -mirror or -sources
# rely on NATS server to check it
set response [my ApiRequest "STREAM.$action.$stream" [nats::_dict2json $spec $args]]
# response fields: config, created (timestamp), state, did_create
set result_config [dict get $response config]
nats::_ns2ms result_config duplicate_window max_age
dict set response config $result_config
return $response
}
method add_stream_from_json {json_config} {
set stream_name [dict get [json::json2dict $json_config] name]
set json_response [$Conn request "$ApiPrefix.STREAM.CREATE.$stream_name" $json_config -timeout $Timeout -dictmsg false]
set dict_response [json::json2dict $json_response]
nats::_checkJsError $dict_response
return $json_response
}
# no request body
# nats schema info --yaml io.nats.jetstream.api.v1.stream_delete_response
method delete_stream {stream} {
set response [my ApiRequest "STREAM.DELETE.$stream" ""]
return [dict get $response success] ;# probably will always be true
}
# nats schema info --yaml io.nats.jetstream.api.v1.stream_purge_request
# nats schema info --yaml io.nats.jetstream.api.v1.stream_purge_response
# https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-10.md
method purge_stream {stream args} {
set spec {filter valid_str null
keep pos_int null
seq pos_int null }
nats::_parse_args $args $spec
set response [my ApiRequest "STREAM.PURGE.$stream" [nats::_local2json $spec]]
return [dict get $response purged]
}
# nats schema info --yaml io.nats.jetstream.api.v1.stream_info_request
# nats schema info --yaml io.nats.jetstream.api.v1.stream_info_response
method stream_info {stream} {
set response [my ApiRequest "STREAM.INFO.$stream" ""]
dict unset response total
dict unset response offset
dict unset response limit
# remaining fields: config, created (timestamp), state
set result_config [dict get $response config]
nats::_ns2ms result_config duplicate_window max_age
dict set response config $result_config
return $response
}
# nats schema info --yaml io.nats.jetstream.api.v1.stream_names_request
# nats schema info --yaml io.nats.jetstream.api.v1.stream_names_response
method stream_names {args} {
set spec {subject valid_str null}
nats::_parse_args $args $spec
set response [my ApiRequest "STREAM.NAMES" [nats::_local2json $spec]]
if {[dict get $response total] == 0} {
return [list]
}
return [dict get $response streams]
}
method bind_kv_bucket {bucket} {
my CheckBucketName $bucket
set stream "KV_$bucket"
try {
set stream_info [my stream_info $stream]
} trap {NATS ErrStreamNotFound} err {
throw {NATS ErrBucketNotFound} "Bucket $bucket not found"
}
if {[dict get $stream_info config max_msgs_per_subject] < 1} {
throw {NATS ErrBucketNotFound} "Bucket $bucket not found"
}
set keyValue [nats::key_value new $Conn [self] $Domain $bucket [dict get $stream_info config]]
set ChildrenRef($keyValue) ""
return $keyValue
}
method create_kv_bucket {bucket args} {
return [my CreateBucket $bucket "" "" false {*}$args]
}
method create_kv_aggregate {bucket writable origins args} {
if {[llength $origins] == 0} {
throw {NATS ErrInvalidArg} "List of KV origins is required"
}
if {![string is boolean -strict $writable]} {
throw {NATS ErrInvalidArg} "writable = $writable is not a boolean"
}
if {"-mirror_name" in $args || "-mirror_domain" in $args} {
throw {NATS ErrInvalidArg} "-mirror_name and -mirror_domain are not allowed"
}
return [my CreateBucket $bucket $writable $origins false {*}$args]
}
method create_kv_mirror {name origin args} {
if {"-mirror_name" in $args || "-mirror_domain" in $args} {
throw {NATS ErrInvalidArg} "-mirror_name and -mirror_domain are not allowed"
}
my CreateBucket $name false $origin true {*}$args
return
}
method CreateBucket {bucket writable origins is_mirror args} {
my CheckBucketName $bucket
set streamName "KV_$bucket"
nats::_parse_args $args {
description valid_str null
max_value_size int null
history pos_int 1
ttl pos_int null
max_bucket_size pos_int null
storage {enum memory file} file
num_replicas int 1
compression {enum none s2} null
mirror_name valid_str null
mirror_domain valid_str null
metadata metadata null
}
if {$history < 1 || $history > 64} {
throw {NATS ErrInvalidArg} "History must be between 1 and 64"
}
set duplicate_window 120000 ;# 2 min
if {[info exists ttl] && $ttl < $duplicate_window} {
set duplicate_window $ttl
}
set stream_config [dict create \
allow_rollup_hdrs true \
deny_delete true \
discard new \
duplicate_window $duplicate_window \
deny_purge false \
max_msgs_per_subject $history \
allow_direct true]
if {[info exists ttl]} {
dict set stream_config max_age $ttl
}
if {[info exists max_value_size]} {
dict set stream_config max_msg_size $max_value_size
}
if {[info exists max_bucket_size]} {
dict set stream_config max_bytes $max_bucket_size
}
foreach opt {description storage num_replicas compression metadata} {
if {[info exists $opt]} {
dict set stream_config $opt [set $opt]
}
}
# -mirror_name and -mirror_domain are deprecated; use create_kv_mirror instead
if {[info exists mirror_name]} {
set srcArgs [list -name "KV_$mirror_name"]
if {[info exists mirror_domain]} {
lappend srcArgs -api "\$JS.$mirror_domain.API"
}
dict set stream_config mirror [nats::make_stream_source {*}$srcArgs]
dict set stream_config mirror_direct true
} else {
dict set stream_config subjects "\$KV.$bucket.>"
}
if {$is_mirror} {
# this is a KV mirror, it can have only one origin, and you can't bind to it
# can't check for [llength $origins] != 1 because it's a dict
dict set stream_config mirror_direct true
dict unset stream_config subjects
if [string match "KV_*" $bucket] {
throw {NATS ErrInvalidArg} "Mirror name must not be KV" ;# ensure users can't bind to it
}
set streamName $bucket
dict set stream_config mirror [my OriginToMirror $origins]
} else {
if [llength $origins] {
# this is a KV aggregate, it can have one or more origins, and you can bind to it
foreach origin $origins {
lappend streamSources [my OriginToSource $origin $bucket]
}
dict set stream_config sources $streamSources
if {$writable} {
dict set stream_config deny_delete false
} else {
dict unset stream_config subjects
}
}
}
set stream_info [my add_stream $streamName {*}$stream_config]
set keyValue [nats::key_value new $Conn [self] $Domain $bucket [dict get $stream_info config]]
set ChildrenRef($keyValue) ""
return $keyValue
}
method OriginToSource {origin new_bucket} {
dict with origin {
if {![info exists stream]} {
set stream "KV_$bucket"
}
if {![info exists keys] || [llength $keys] == 0} {
lappend keys >
}
foreach key $keys {
lappend transforms [nats::make_subject_transform -src "\$KV.$bucket.$key" -dest "\$KV.$new_bucket.$key"]
}
set srcArgs [list -name $stream -subject_transforms $transforms]
if [info exists api] {
lappend srcArgs -api $api
if [info exists deliver] {
lappend srcArgs -deliver $deliver
}
}
nats::make_stream_source {*}$srcArgs ;# implicit return
}
}
method OriginToMirror {origin} {
dict with origin {
set srcArgs [list -name "KV_$bucket"]
if {[info exists keys] && [llength $keys]} {
foreach key $keys {
lappend transforms [nats::make_subject_transform -src "\$KV.$bucket.$key" -dest "\$KV.$bucket.$key"]
}
lappend srcArgs -subject_transforms $transforms
}
if [info exists api] {
lappend srcArgs -api $api
if [info exists deliver] {
lappend srcArgs -deliver $deliver
}
}
nats::make_stream_source {*}$srcArgs ;# implicit return
}
}
method delete_kv_bucket {bucket} {
my CheckBucketName $bucket
set stream "KV_$bucket"
try {
return [my delete_stream $stream]
} trap {NATS ErrStreamNotFound} err {
throw {NATS ErrBucketNotFound} "Bucket $bucket not found"
}
}
method kv_buckets {} {
set kv_list [list]
foreach stream [my stream_names] {
if {[string range $stream 0 2] eq "KV_"} {
lappend kv_list [string range $stream 3 end]
}
}
return $kv_list
}
method empty_kv_bucket {bucket} {
return [my purge_stream "KV_$bucket"]
}
# nats schema info --yaml io.nats.jetstream.api.v1.account_info_response
method account_info {} {
return [my ApiRequest "INFO" ""]
}
method CheckBucketName {bucket} {
if {![regexp {^[a-zA-Z0-9_-]+$} $bucket]} {
throw {NATS ErrInvalidArg} "Invalid bucket name $bucket"
}
}
# userCallback args: timedOut pubAck error
method PublishCallback {userCallback timedOut msg} {
if {$timedOut} {
# also in case of no-responders
after 0 [list {*}$userCallback 1 "" ""]
return
}
set response [json::json2dict $msg]
if {![dict exists $response error]} {
after 0 [list {*}$userCallback 0 $response ""]
return
}
# make the same dict as in AsyncError, with extra field err_code
set js_error [dict get $response error]
dict set js_error errorMessage [dict get $js_error description]
dict unset js_error description
after 0 [list {*}$userCallback 0 "" $js_error]
}
# https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-6.md
# only the Unix variant, also no " [] {}
method CheckFilenameSafe {str} {
return [regexp -- {^[-[:alnum:]!#$%&()+,:;<=?@^_`|~]+$} $str]
}
method ApiRequest {subj msg {checkSubj true}} {
try {
if {$Trace} {
[info object namespace $Conn]::log::debug ">>> $ApiPrefix.$subj $msg"
}
set replyJson [$Conn request "$ApiPrefix.$subj" $msg -timeout $Timeout -dictmsg false -check_subj $checkSubj]
if {$Trace} {
[info object namespace $Conn]::log::debug "<<< $ApiPrefix.$subj $replyJson"
}
set response [json::json2dict $replyJson]
} trap {NATS ErrNoResponders} err {
throw {NATS ErrJetStreamNotEnabled} "JetStream is not enabled in the server"
}
nats::_checkJsError $response
dict unset response type ;# no-op if the key doesn't exist
return $response
}
}
# see ADR-15 and ADR-17
oo::class create ::nats::ordered_consumer {
variable Conn Js Stream Config StreamSeq ConsumerSeq Name SubID UserCb Timer PostEvent RetryInterval ConsumerInfo
# "public" variable
variable last_error
constructor {connection jet_stream streamName conf cb post} {
set Conn $connection
set Js $jet_stream
set Stream $streamName
set UserCb $cb
set StreamSeq 0
set ConsumerSeq 0
set Name ""
set SubID ""
set Timer "" ;# used both for HB and reset retries
set RetryInterval 10000 ;# same as in nats.go/jetstream/ordered.go
set PostEvent $post
set Config [dict replace $conf \
flow_control true \
ack_policy none \
max_deliver 1 \
ack_wait [expr {22 * 3600 * 1000}] \
num_replicas 1 \
mem_storage true \
inactive_threshold 2000]
set last_error ""
my Reset
}
destructor {
after cancel $Timer
if {$PostEvent} {
$Js releaseRef [self]
}
if {$SubID eq ""} {
return
}
try {
$Conn unsubscribe $SubID ;# NATS will delete the ephemeral consumer
} trap {NATS ErrConnectionClosed} err {}
}
method Reset {{errCode ""}} {
set inbox "_INBOX.[nats::_random_string]"
dict set Config deliver_subject $inbox
if {$errCode ne ""} {
dict set Config deliver_policy by_start_sequence
set startSeq [expr {$StreamSeq + 1}]
dict set Config opt_start_seq $startSeq
my AsyncError $errCode "reset with opt_start_seq = $startSeq due to $errCode"
}
if {$errCode eq ""} {
set ConsumerInfo [$Js add_consumer $Stream {*}$Config] ;# let any error propagate to the caller
} else {
# we are working in the background, so all errors must be reported via AsyncError
try {
set ConsumerInfo [$Js add_consumer $Stream {*}$Config]
} trap {NATS ErrStreamNotFound} {err opts} {
my AsyncError ErrStreamNotFound "stopped due to $err"
return ;# can't recover from this
} trap {NATS} {err opts} {
# most likely ErrTimeout if we're reconnecting to NATS or ErrJetStreamNotEnabled if a JetStream cluster is electing a new leader
my AsyncError [lindex [dict get $opts -errorcode] 1] "failed to reset: $err"
if {[$Conn cget status] == $nats::status_closed} {
my AsyncError ErrConnectionClosed "stopped"
return
}
# default delay is 10s to avoid spamming the log with warnings
my ScheduleReset $errCode $RetryInterval
return
}
}
set Config [dict get $ConsumerInfo config]
set Name [dict get $ConsumerInfo name]
set StreamSeq [dict get $ConsumerInfo delivered stream_seq]
set ConsumerSeq [dict get $ConsumerInfo delivered consumer_seq]
set SubID [$Conn subscribe $inbox -dictmsg true -callback [nats::mymethod OnMsg] -post false]
my RestartHbTimer
[info object namespace $Conn]::log::debug "Ordered consumer $Name subscribed to $Stream, stream_seq = $StreamSeq, filter = [dict get $Config filter_subject]"
}
method RestartHbTimer {} {
after cancel $Timer
# reset if we don't receive any message within interval*3 ms; works also if somebody deletes the consumer in NATS
set Timer [after [expr {[dict get $Config idle_heartbeat] * 3}] [nats::mymethod OnMissingHb]]
}
method ScheduleReset {errCode {delay 0}} {
set Name "" ;# make the name blank while reset in is progress
after cancel $Timer ;# stop the HB timer
if {$SubID ne ""} {
$Conn unsubscribe $SubID ;# unsub immediately to avoid OnMsg being called again while reset is in progress
set SubID ""
}
set Timer [after $delay [nats::mymethod Reset $errCode]] ;# due to -post=false we are inside the coroutine, so can't call reset directly
}
method OnMsg {subj msg reply} {
my RestartHbTimer
if {[nats::msg idle_heartbeat $msg]} {
set flowControlReply [nats::header lookup $msg Nats-Consumer-Stalled ""]
if {$flowControlReply ne ""} {
$Conn publish $flowControlReply ""
}
set cseq [nats::header get $msg Nats-Last-Consumer]
if {$cseq == $ConsumerSeq} {
return
}
my ScheduleReset ErrConsumerSequenceMismatch
return
} elseif {[nats::msg flow_control $msg]} {
$Js ack $msg
return
}
set meta [nats::metadata $msg]
set cseq [dict get $meta consumer_seq]
if {$cseq != $ConsumerSeq + 1} {
my ScheduleReset ErrConsumerSequenceMismatch
return