-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathclient.rb
2049 lines (1691 loc) · 60.2 KB
/
client.rb
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
# frozen_string_literal: true
# Copyright 2016-2021 The NATS Authors
# 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.
#
require_relative "parser"
require_relative "version"
require_relative "errors"
require_relative "msg"
require_relative "subscription"
require_relative "jetstream"
require "nats/nuid"
require "socket"
require "json"
require "monitor"
require "uri"
require "securerandom"
require "concurrent"
begin
require "openssl"
rescue LoadError
end
module NATS
class << self
# NATS.connect creates a connection to the NATS Server.
# @param uri [String] URL endpoint of the NATS Server or cluster.
# @param opts [Hash] Options to customize the NATS connection.
# @return [NATS::Client]
#
# @example
# require 'nats'
# nc = NATS.connect("demo.nats.io")
# nc.publish("hello", "world")
# nc.close
#
def connect(uri = nil, opts = {})
nc = NATS::Client.new
nc.connect(uri, opts)
nc
end
end
# Status represents the different states from a NATS connection.
# A client starts from the DISCONNECTED state to CONNECTING during
# the initial connect, then CONNECTED. If the connection is reset
# then it goes from DISCONNECTED to RECONNECTING until it is back to
# the CONNECTED state. In case the client gives up reconnecting or
# the connection is manually closed then it will reach the CLOSED
# connection state after which it will not reconnect again.
module Status
# When the client is not actively connected.
DISCONNECTED = 0
# When the client is connected.
CONNECTED = 1
# When the client will no longer attempt to connect to a NATS Server.
CLOSED = 2
# When the client has disconnected and is attempting to reconnect.
RECONNECTING = 3
# When the client is attempting to connect to a NATS Server for the first time.
CONNECTING = 4
# When the client is draining a connection before closing.
DRAINING_SUBS = 5
DRAINING_PUBS = 6
end
# Fork Detection handling
# Based from similar approach as mperham/connection_pool: https://github.com/mperham/connection_pool/pull/166
if Process.respond_to?(:fork) && Process.respond_to?(:_fork) # MRI 3.1+
module ForkTracker
def _fork
super.tap do |pid|
Client.after_fork if pid.zero? # in the child process
end
end
end
Process.singleton_class.prepend(ForkTracker)
end
# Client creates a connection to the NATS Server.
class Client
include MonitorMixin
include Status
attr_reader :status, :server_info, :server_pool, :options, :stats, :uri, :subscription_executor, :reloader
DEFAULT_PORT = {nats: 4222, ws: 80, wss: 443}.freeze
DEFAULT_URI = "nats://localhost:#{DEFAULT_PORT[:nats]}".freeze
CR_LF = "\r\n"
CR_LF_SIZE = CR_LF.bytesize
PING_REQUEST = "PING#{CR_LF}".freeze
PONG_RESPONSE = "PONG#{CR_LF}".freeze
NATS_HDR_LINE = "NATS/1.0#{CR_LF}".freeze
STATUS_MSG_LEN = 3
STATUS_HDR = "Status"
DESC_HDR = "Description"
NATS_HDR_LINE_SIZE = NATS_HDR_LINE.bytesize
SUB_OP = "SUB"
EMPTY_MSG = ""
INSTANCES = ObjectSpace::WeakMap.new # tracks all alive client instances
private_constant :INSTANCES
class << self
# Reloader should free resources managed by external framework
# that were implicitly acquired in subscription callbacks.
attr_writer :default_reloader
def default_reloader
@default_reloader ||= proc { |&block| block.call }.tap { |r| Ractor.make_shareable(r) if defined? Ractor }
end
# Re-establish connection in a new process after forking to start new threads.
def after_fork
INSTANCES.each do |client|
next if client.closed?
if client.options[:reconnect]
was_connected = !client.disconnected?
client.send(:close_connection, Status::DISCONNECTED, true)
client.connect if was_connected
else
client.send(:err_cb_call, self, NATS::IO::ForkDetectedError, nil)
client.close
end
rescue => e
warn "nats: Error during handling after_fork callback: #{e}" # TODO: Report as async error via error callback?
end
end
end
def initialize(uri = nil, opts = {})
super() # required to initialize monitor
@initial_uri = uri
@initial_options = opts
# Read/Write IO
@io = nil
# Queues for coalescing writes of commands we need to send to server.
@flush_queue = nil
@pending_queue = nil
# Parser with state
@parser = NATS::Protocol::Parser.new(self)
# Threads for both reading and flushing command
@flusher_thread = nil
@read_loop_thread = nil
@ping_interval_thread = nil
# Info that we get from the server
@server_info = {}
# URI from server to which we are currently connected
@uri = nil
@server_pool = []
@status = nil
# Subscriptions
@subs = {}
@ssid = 0
# Ping interval
@pings_outstanding = 0
@pongs_received = 0
@pongs = []
@pongs.extend(MonitorMixin)
# Accounting
@pending_size = 0
@stats = {
in_msgs: 0,
out_msgs: 0,
in_bytes: 0,
out_bytes: 0,
reconnects: 0
}
# Sticky error
@last_err = nil
# Async callbacks, no ops by default.
@err_cb = proc {}
@close_cb = proc {}
@disconnect_cb = proc {}
@reconnect_cb = proc {}
# Secure TLS options
@tls = nil
# Hostname of current server; used for when TLS host
# verification is enabled.
@hostname = nil
@single_url_connect_used = false
# Track whether connect has been already been called.
@connect_called = false
# New style request/response implementation.
@resp_sub = nil
@resp_map = nil
@resp_sub_prefix = nil
@nuid = NATS::NUID.new
# NKEYS
@user_credentials = nil
@nkeys_seed = nil
@user_nkey_cb = nil
@user_jwt_cb = nil
@signature_cb = nil
# Tokens
@auth_token = nil
@inbox_prefix = "_INBOX"
# Draining
@drain_t = nil
# Prepare for calling connect or automatic delayed connection
parse_and_validate_options if uri || opts.any?
# Keep track of all client instances to handle them after process forking in Ruby 3.1+
INSTANCES[self] = self if !defined?(Ractor) || Ractor.current == Ractor.main # Ractors doesn't work in forked processes
@reloader = opts.fetch(:reloader, self.class.default_reloader)
end
# Prepare connecting to NATS, but postpone real connection until first usage.
def connect(uri = nil, opts = {})
if uri || opts.any?
@initial_uri = uri
@initial_options = opts
end
synchronize do
# In case it has been connected already, then do not need to call this again.
return if @connect_called
@connect_called = true
end
parse_and_validate_options
establish_connection!
self
end
private def parse_and_validate_options
# Reset these in case we have reconnected via fork.
@server_pool = []
@resp_sub = nil
@resp_map = nil
@resp_sub_prefix = nil
@nuid = NATS::NUID.new
@stats = {
in_msgs: 0,
out_msgs: 0,
in_bytes: 0,
out_bytes: 0,
reconnects: 0
}
@status = DISCONNECTED
# Convert URI to string if needed.
uri = @initial_uri.dup
uri = uri.to_s if uri.is_a?(URI)
opts = @initial_options.dup
case uri
when String
# Initialize TLS defaults in case any url is using it.
srvs = opts[:servers] = process_uri(uri)
if srvs.any? { |u| %w[tls wss].include? u.scheme } && !opts[:tls]
opts[:tls] = {context: tls_context}
end
@single_url_connect_used = true if srvs.size == 1
when Hash
opts = uri
end
opts[:verbose] = false if opts[:verbose].nil?
opts[:pedantic] = false if opts[:pedantic].nil?
opts[:reconnect] = true if opts[:reconnect].nil?
opts[:old_style_request] = false if opts[:old_style_request].nil?
opts[:ignore_discovered_urls] = false if opts[:ignore_discovered_urls].nil?
opts[:reconnect_time_wait] = NATS::IO::RECONNECT_TIME_WAIT if opts[:reconnect_time_wait].nil?
opts[:max_reconnect_attempts] = NATS::IO::MAX_RECONNECT_ATTEMPTS if opts[:max_reconnect_attempts].nil?
opts[:ping_interval] = NATS::IO::DEFAULT_PING_INTERVAL if opts[:ping_interval].nil?
opts[:max_outstanding_pings] = NATS::IO::DEFAULT_PING_MAX if opts[:max_outstanding_pings].nil?
# Override with ENV
opts[:verbose] = ENV["NATS_VERBOSE"].downcase == "true" unless ENV["NATS_VERBOSE"].nil?
opts[:pedantic] = ENV["NATS_PEDANTIC"].downcase == "true" unless ENV["NATS_PEDANTIC"].nil?
opts[:reconnect] = ENV["NATS_RECONNECT"].downcase == "true" unless ENV["NATS_RECONNECT"].nil?
opts[:reconnect_time_wait] = ENV["NATS_RECONNECT_TIME_WAIT"].to_i unless ENV["NATS_RECONNECT_TIME_WAIT"].nil?
opts[:ignore_discovered_urls] = ENV["NATS_IGNORE_DISCOVERED_URLS"].downcase == "true" unless ENV["NATS_IGNORE_DISCOVERED_URLS"].nil?
opts[:max_reconnect_attempts] = ENV["NATS_MAX_RECONNECT_ATTEMPTS"].to_i unless ENV["NATS_MAX_RECONNECT_ATTEMPTS"].nil?
opts[:ping_interval] = ENV["NATS_PING_INTERVAL"].to_i unless ENV["NATS_PING_INTERVAL"].nil?
opts[:max_outstanding_pings] = ENV["NATS_MAX_OUTSTANDING_PINGS"].to_i unless ENV["NATS_MAX_OUTSTANDING_PINGS"].nil?
opts[:connect_timeout] ||= NATS::IO::DEFAULT_CONNECT_TIMEOUT
opts[:drain_timeout] ||= NATS::IO::DEFAULT_DRAIN_TIMEOUT
opts[:close_timeout] ||= NATS::IO::DEFAULT_CLOSE_TIMEOUT
@options = opts
# Process servers in the NATS cluster and pick one to connect
uris = opts[:servers] || [DEFAULT_URI]
uris.shuffle! unless @options[:dont_randomize_servers]
uris.each do |u|
nats_uri = case u
when URI
u.dup
else
URI.parse(u)
end
@server_pool << {
uri: nats_uri,
hostname: nats_uri.hostname
}
end
if @options[:old_style_request]
# Replace for this instance the implementation
# of request to use the old_request style.
class << self; alias_method :request, :old_request; end
end
# NKEYS
@signature_cb ||= opts[:user_signature_cb]
@user_jwt_cb ||= opts[:user_jwt_cb]
@user_nkey_cb ||= opts[:user_nkey_cb]
@user_credentials ||= opts[:user_credentials]
@nkeys_seed ||= opts[:nkeys_seed]
setup_nkeys_connect if @user_credentials || @nkeys_seed
# Tokens, if set will take preference over the user@server uri token
@auth_token ||= opts[:auth_token]
# Check for TLS usage
@tls = @options[:tls]
@inbox_prefix = opts.fetch(:custom_inbox_prefix, @inbox_prefix)
validate_settings!
self
end
private def establish_connection!
@ruby_pid = Process.pid # For fork detection
srv = nil
begin
srv = select_next_server
# Use the hostname from the server for TLS hostname verification.
if client_using_secure_connection? && single_url_connect_used?
# Always reuse the original hostname used to connect.
@hostname ||= srv[:hostname]
else
@hostname = srv[:hostname]
end
# Create TCP socket connection to NATS.
@io = create_socket
@io.connect
# Capture state that we have had a TCP connection established against
# this server and could potentially be used for reconnecting.
srv[:was_connected] = true
# Connection established and now in process of sending CONNECT to NATS
@status = CONNECTING
# Established TCP connection successfully so can start connect
process_connect_init
# Reset reconnection attempts if connection is valid
srv[:reconnect_attempts] = 0
srv[:auth_required] ||= true if @server_info[:auth_required]
# Add back to rotation since successfully connected
server_pool << srv
rescue NATS::IO::NoServersError => e
@disconnect_cb.call(e) if @disconnect_cb
raise @last_err || e
rescue => e
# Capture sticky error
synchronize do
@last_err = e
srv[:auth_required] ||= true if @server_info[:auth_required]
server_pool << srv if can_reuse_server?(srv)
end
err_cb_call(self, e, nil) if @err_cb
if should_not_reconnect?
@disconnect_cb.call(e) if @disconnect_cb
raise e
end
# Clean up any connecting state and close connection without
# triggering the disconnection/closed callbacks.
close_connection(DISCONNECTED, false)
# Always sleep here to safe guard against errors before current[:was_connected]
# is set for the first time.
sleep @options[:reconnect_time_wait] if @options[:reconnect_time_wait]
# Continue retrying until there are no options left in the server pool
retry
end
# Initialize queues and loops for message dispatching and processing engine
@flush_queue = SizedQueue.new(NATS::IO::MAX_FLUSH_KICK_SIZE)
@pending_queue = SizedQueue.new(NATS::IO::MAX_PENDING_SIZE)
@pings_outstanding = 0
@pongs_received = 0
@pending_size = 0
# Server roundtrip went ok so consider to be connected at this point
@status = CONNECTED
# Connected to NATS so Ready to start parser loop, flusher and ping interval
start_threads!
self
end
def publish(subject, msg = EMPTY_MSG, opt_reply = nil, **options, &blk)
raise NATS::IO::BadSubject if !subject || subject.empty?
if options[:header]
return publish_msg(NATS::Msg.new(subject: subject, data: msg, reply: opt_reply, header: options[:header]))
end
# Accounting
msg_size = msg.bytesize
@stats[:out_msgs] += 1
@stats[:out_bytes] += msg_size
send_command("PUB #{subject} #{opt_reply} #{msg_size}\r\n#{msg}\r\n")
@flush_queue << :pub if @flush_queue.empty?
end
# Publishes a NATS::Msg that may include headers.
def publish_msg(msg)
raise TypeError, "nats: expected NATS::Msg, got #{msg.class.name}" unless msg.is_a?(Msg)
raise NATS::IO::BadSubject if !msg.subject || msg.subject.empty?
msg.reply ||= "".dup
msg.data ||= "".dup
msg_size = msg.data.bytesize
# Accounting
@stats[:out_msgs] += 1
@stats[:out_bytes] += msg_size
if msg.header
hdr = "".dup
hdr << NATS_HDR_LINE
msg.header.each do |k, v|
hdr << "#{k}: #{v}#{CR_LF}"
end
hdr << CR_LF
hdr_len = hdr.bytesize
total_size = msg_size + hdr_len
send_command("HPUB #{msg.subject} #{msg.reply} #{hdr_len} #{total_size}\r\n#{hdr}#{msg.data}\r\n")
else
send_command("PUB #{msg.subject} #{msg.reply} #{msg_size}\r\n#{msg.data}\r\n")
end
@flush_queue << :pub if @flush_queue.empty?
end
# Create subscription which is dispatched asynchronously
# messages to a callback.
def subscribe(subject, opts = {}, &callback)
raise NATS::IO::ConnectionDrainingError.new("nats: connection draining") if draining?
sid = nil
sub = nil
synchronize do
sid = (@ssid += 1)
sub = @subs[sid] = Subscription.new
sub.nc = self
sub.sid = sid
end
opts[:pending_msgs_limit] ||= NATS::IO::DEFAULT_SUB_PENDING_MSGS_LIMIT
opts[:pending_bytes_limit] ||= NATS::IO::DEFAULT_SUB_PENDING_BYTES_LIMIT
sub.subject = subject
sub.callback = callback
sub.received = 0
sub.queue = opts[:queue] if opts[:queue]
sub.max = opts[:max] if opts[:max]
sub.pending_msgs_limit = opts[:pending_msgs_limit]
sub.pending_bytes_limit = opts[:pending_bytes_limit]
sub.pending_queue = SizedQueue.new(sub.pending_msgs_limit)
sub.processing_concurrency = opts[:processing_concurrency] if opts.key?(:processing_concurrency)
send_command("SUB #{subject} #{opts[:queue]} #{sid}#{CR_LF}")
@flush_queue << :sub
# Setup server support for auto-unsubscribe when receiving enough messages
sub.unsubscribe(opts[:max]) if opts[:max]
unless callback
cond = sub.new_cond
sub.wait_for_msgs_cond = cond
end
sub
end
# Sends a request using expecting a single response using a
# single subscription per connection for receiving the responses.
# It times out in case the request is not retrieved within the
# specified deadline.
# If given a callback, then the request happens asynchronously.
def request(subject, payload = "", **opts, &blk)
raise NATS::IO::BadSubject if !subject || subject.empty?
# If a block was given then fallback to method using auto unsubscribe.
return old_request(subject, payload, opts, &blk) if blk
return old_request(subject, payload, opts) if opts[:old_style]
if opts[:header]
return request_msg(NATS::Msg.new(subject: subject, data: payload, header: opts[:header]), **opts)
end
token = nil
inbox = nil
future = nil
response = nil
timeout = opts[:timeout] ||= 0.5
synchronize do
start_resp_mux_sub! unless @resp_sub_prefix
# Create token for this request.
token = @nuid.next
inbox = "#{@resp_sub_prefix}.#{token}"
# Create the a future for the request that will
# get signaled when it receives the request.
future = @resp_sub.new_cond
@resp_map[token][:future] = future
end
# Publish request and wait for reply.
publish(subject, payload, inbox)
begin
MonotonicTime.with_nats_timeout(timeout) do
@resp_sub.synchronize do
future.wait(timeout)
end
end
rescue NATS::Timeout => e
synchronize { @resp_map.delete(token) }
raise e
end
# Check if there is a response already.
synchronize do
result = @resp_map[token]
response = result[:response]
@resp_map.delete(token)
end
if response&.header
status = response.header[STATUS_HDR]
raise NATS::IO::NoRespondersError if status == "503"
end
response
end
# request_msg makes a NATS request using a NATS::Msg that may include headers.
def request_msg(msg, **opts)
raise TypeError, "nats: expected NATS::Msg, got #{msg.class.name}" unless msg.is_a?(Msg)
raise NATS::IO::BadSubject if !msg.subject || msg.subject.empty?
token = nil
inbox = nil
future = nil
response = nil
timeout = opts[:timeout] ||= 0.5
synchronize do
start_resp_mux_sub! unless @resp_sub_prefix
# Create token for this request.
token = @nuid.next
inbox = "#{@resp_sub_prefix}.#{token}"
# Create the a future for the request that will
# get signaled when it receives the request.
future = @resp_sub.new_cond
@resp_map[token][:future] = future
end
msg.reply = inbox
msg.data ||= ""
msg.data.bytesize
# Publish request and wait for reply.
publish_msg(msg)
begin
MonotonicTime.with_nats_timeout(timeout) do
@resp_sub.synchronize do
future.wait(timeout)
end
end
rescue NATS::Timeout => e
synchronize { @resp_map.delete(token) }
raise e
end
# Check if there is a response already.
synchronize do
result = @resp_map[token]
response = result[:response]
@resp_map.delete(token)
end
if response&.header
status = response.header[STATUS_HDR]
raise NATS::IO::NoRespondersError if status == "503"
end
response
end
# Sends a request creating an ephemeral subscription for the request,
# expecting a single response or raising a timeout in case the request
# is not retrieved within the specified deadline.
# If given a callback, then the request happens asynchronously.
def old_request(subject, payload, opts = {}, &blk)
return unless subject
inbox = new_inbox
# If a callback was passed, then have it process
# the messages asynchronously and return the sid.
if blk
opts[:max] ||= 1
s = subscribe(inbox, opts) do |msg|
case blk.arity
when 0 then blk.call
when 1 then blk.call(msg)
when 2 then blk.call(msg.data, msg.reply)
when 3 then blk.call(msg.data, msg.reply, msg.subject)
else blk.call(msg.data, msg.reply, msg.subject, msg.header)
end
end
publish(subject, payload, inbox)
return s
end
# In case block was not given, handle synchronously
# with a timeout and only allow a single response.
timeout = opts[:timeout] ||= 0.5
opts[:max] = 1
sub = Subscription.new
sub.subject = inbox
sub.received = 0
future = sub.new_cond
sub.future = future
sub.nc = self
sid = nil
synchronize do
sid = (@ssid += 1)
sub.sid = sid
@subs[sid] = sub
end
send_command("SUB #{inbox} #{sid}#{CR_LF}")
@flush_queue << :sub
unsubscribe(sub, 1)
sub.synchronize do
# Publish the request and then wait for the response...
publish(subject, payload, inbox)
MonotonicTime.with_nats_timeout(timeout) do
future.wait(timeout)
end
end
response = sub.response
if response&.header
status = response.header[STATUS_HDR]
raise NATS::IO::NoRespondersError if status == "503"
end
response
end
# Send a ping and wait for a pong back within a timeout.
def flush(timeout = 10)
# Schedule sending a PING, and block until we receive PONG back,
# or raise a timeout in case the response is past the deadline.
pong = @pongs.new_cond
@pongs.synchronize do
@pongs << pong
# Flush once pong future has been prepared
@pending_queue << PING_REQUEST
@flush_queue << :ping
MonotonicTime.with_nats_timeout(timeout) do
pong.wait(timeout)
end
end
end
alias_method :servers, :server_pool
# discovered_servers returns the NATS Servers that have been discovered
# via INFO protocol updates.
def discovered_servers
servers.select { |s| s[:discovered] }
end
# Close connection to NATS, flushing in case connection is alive
# and there are any pending messages, should not be used while
# holding the lock.
def close
close_connection(CLOSED, true)
end
# new_inbox returns a unique inbox used for subscriptions.
# @return [String]
def new_inbox
"#{@inbox_prefix}.#{@nuid.next}"
end
def connected_server
connected? ? @uri : nil
end
def disconnected?
!@status or @status == DISCONNECTED
end
def connected?
@status == CONNECTED
end
def connecting?
@status == CONNECTING
end
def reconnecting?
@status == RECONNECTING
end
def closed?
@status == CLOSED
end
def draining?
if (@status == DRAINING_PUBS) || (@status == DRAINING_SUBS)
return true
end
is_draining = false
synchronize do
is_draining = true if @drain_t
end
is_draining
end
def on_error(&callback)
@err_cb = callback
end
def on_disconnect(&callback)
@disconnect_cb = callback
end
def on_reconnect(&callback)
@reconnect_cb = callback
end
def on_close(&callback)
@close_cb = callback
end
def last_error
synchronize do
@last_err
end
end
# drain will put a connection into a drain state. All subscriptions will
# immediately be put into a drain state. Upon completion, the publishers
# will be drained and can not publish any additional messages. Upon draining
# of the publishers, the connection will be closed. Use the `on_close`
# callback option to know when the connection has moved from draining to closed.
def drain
return if draining?
synchronize do
@drain_t ||= Thread.new { do_drain }
end
end
# Create a JetStream context.
# @param opts [Hash] Options to customize the JetStream context.
# @option params [String] :prefix JetStream API prefix to use for the requests.
# @option params [String] :domain JetStream Domain to use for the requests.
# @option params [Float] :timeout Default timeout to use for JS requests.
# @return [NATS::JetStream]
def jetstream(opts = {})
::NATS::JetStream.new(self, opts)
end
alias_method :JetStream, :jetstream
alias_method :jsm, :jetstream
private
def validate_settings!
raise(NATS::IO::ClientError, "custom inbox may not include '>'") if @inbox_prefix.include?(">")
raise(NATS::IO::ClientError, "custom inbox may not include '*'") if @inbox_prefix.include?("*")
raise(NATS::IO::ClientError, "custom inbox may not end in '.'") if @inbox_prefix.end_with?(".")
raise(NATS::IO::ClientError, "custom inbox may not begin with '.'") if @inbox_prefix.start_with?(".")
end
def process_info(line)
parsed_info = JSON.parse(line)
# INFO can be received asynchronously too,
# so has to be done under the lock.
synchronize do
# Symbolize keys from parsed info line
@server_info = parsed_info.each_with_object({}) do |(k, v), info|
info[k.to_sym] = v
end
# Detect any announced server that we might not be aware of...
connect_urls = @server_info[:connect_urls]
if !@options[:ignore_discovered_urls] && connect_urls
srvs = []
connect_urls.each do |url|
# Use the same scheme as the currently in use URI.
scheme = @uri.scheme
u = URI.parse("#{scheme}://#{url}")
# Skip in case it is the current server which we already know
next if @uri.hostname == u.hostname && @uri.port == u.port
present = server_pool.detect do |srv|
srv[:uri].hostname == u.hostname && srv[:uri].port == u.port
end
if !present
# Let explicit user and pass options set the credentials.
u.user = options[:user] if options[:user]
u.password = options[:pass] if options[:pass]
# Use creds from the current server if not set explicitly.
if @uri
u.user ||= @uri.user if @uri.user
u.password ||= @uri.password if @uri.password
end
# NOTE: Auto discovery won't work here when TLS host verification is enabled.
srv = {uri: u, reconnect_attempts: 0, discovered: true, hostname: u.hostname}
srvs << srv
end
end
srvs.shuffle! unless @options[:dont_randomize_servers]
# Include in server pool but keep current one as the first one.
server_pool.push(*srvs)
end
end
@server_info
end
def process_hdr(header)
hdr = nil
if header
hdr = {}
lines = header.lines
# Check if the first line has an inline status and description.
if lines.count > 0
status_hdr = lines.first.rstrip
status = status_hdr.slice(NATS_HDR_LINE_SIZE - 1, STATUS_MSG_LEN)
if status && !status.empty?
hdr[STATUS_HDR] = status
if NATS_HDR_LINE_SIZE + 2 < status_hdr.bytesize
desc = status_hdr.slice(NATS_HDR_LINE_SIZE + STATUS_MSG_LEN, status_hdr.bytesize)
hdr[DESC_HDR] = desc unless desc.empty?
end
end
end
begin
lines.slice(1, header.size).each do |line|
line.rstrip!
next if line.empty?
key, value = line.strip.split(/\s*:\s*/, 2)
hdr[key] = value
end
rescue => e
e
end
end
hdr
end
# Methods only used by the parser
def process_pong
# Take first pong wait and signal any flush in case there was one
@pongs.synchronize do
pong = @pongs.pop
pong&.signal
end
@pings_outstanding -= 1
@pongs_received += 1
end
# Received a ping so respond back with a pong
def process_ping
@pending_queue << PONG_RESPONSE
@flush_queue << :ping
pong = @pongs.new_cond
@pongs.synchronize { @pongs << pong }
end
# Handles protocol errors being sent by the server.
def process_err(err)
# In case of permissions violation then dispatch the error callback
# while holding the lock.
e = synchronize do
current = server_pool.first
if err =~ /'Stale Connection'/
@last_err = NATS::IO::StaleConnectionError.new(err)
elsif current && current[:auth_required]
# We cannot recover from auth errors so mark it to avoid
# retrying to unecessarily next time.
current[:error_received] = true
@last_err = NATS::IO::AuthError.new(err)
else
@last_err = NATS::IO::ServerError.new(err)
end
end
process_op_error(e)
end
def process_msg(subject, sid, reply, data, header)
@stats[:in_msgs] += 1
@stats[:in_bytes] += data.size
# Throw away in case we no longer manage the subscription
sub = nil
synchronize { sub = @subs[sid] }
return unless sub
err = nil
sub.synchronize do
sub.received += 1
# Check for auto_unsubscribe
if sub.max
case
when sub.received > sub.max
# Client side support in case server did not receive unsubscribe