Class: Protobuf::Nats::Client

Inherits:
Rpc::Connectors::Base
  • Object
show all
Defined in:
lib/protobuf/nats/client.rb

Defined Under Namespace

Classes: SubscriptionInbox

Constant Summary collapse

RESPONSE_MUXER =
::Protobuf::Nats::ResponseMuxer.new
CONCURRENT_SUBSCRIPTION_CACHE =

On JRuby (true parallelism) concurrent writes to a plain nested Hash can raise ConcurrentModificationError / corrupt the map, so the cache must be a Concurrent::Map. On CRuby the GVL makes plain-Hash reads/writes atomic (a racing ‘||=` at worst recomputes an identical value), and a plain Hash is meaningfully faster than Concurrent::Map, so we keep the Hash there.

(::RUBY_ENGINE == "jruby")

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Client

Returns a new instance of Client.



66
67
68
69
70
71
72
73
74
75
# File 'lib/protobuf/nats/client.rb', line 66

def initialize(options)
  # may need to override to setup connection at this stage ... may also do on load of class
  super

  # This will ensure the client is started.
  ::Protobuf::Nats.start_client_nats_connection

  # Ensure the response muxer is started
  RESPONSE_MUXER.start
end

Class Method Details

.subscription_key_cacheObject



107
108
109
# File 'lib/protobuf/nats/client.rb', line 107

def self.subscription_key_cache
  @subscription_key_cache
end

.subscription_poolObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/protobuf/nats/client.rb', line 43

def self.subscription_pool
  return @subscription_pool if @subscription_pool

  @subscription_pool_lock.synchronize do
    # The double-check ensures we don't create a new pool if another
    # thread created one while we were waiting for the lock.
    return @subscription_pool if @subscription_pool

    @subscription_pool = ::ConnectionPool.new(:size => subscription_pool_size, :timeout => 0.1) do
      inbox = ::Protobuf::Nats.client_nats_connection.new_inbox
      SubscriptionInbox.new(::Protobuf::Nats.client_nats_connection.subscribe(inbox), inbox)
    end
  end
end

.subscription_pool_sizeObject



58
59
60
61
62
63
64
# File 'lib/protobuf/nats/client.rb', line 58

def self.subscription_pool_size
  @subscription_pool_size ||= if ::ENV.key?("PB_NATS_CLIENT_SUBSCRIPTION_POOL_SIZE")
    ::ENV["PB_NATS_CLIENT_SUBSCRIPTION_POOL_SIZE"].to_i
  else
    0
  end
end

Instance Method Details

#ack_timeoutObject



111
112
113
114
115
116
117
# File 'lib/protobuf/nats/client.rb', line 111

def ack_timeout
  @ack_timeout ||= if ::ENV.key?("PB_NATS_CLIENT_ACK_TIMEOUT")
    ::ENV["PB_NATS_CLIENT_ACK_TIMEOUT"].to_i
  else
    5
  end
end

#cached_subscription_keyObject



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/protobuf/nats/client.rb', line 215

def cached_subscription_key
  klass = @options[:service]
  method_name = @options[:method]

  cache = self.class.subscription_key_cache
  if CONCURRENT_SUBSCRIPTION_CACHE
    method_name_cache = cache.compute_if_absent(klass) { ::Concurrent::Map.new }
    method_name_cache.compute_if_absent(method_name) do
      ::Protobuf::Nats.subscription_key(klass, method_name)
    end
  else
    method_name_cache = cache[klass] ||= {}
    method_name_cache[method_name] ||= ::Protobuf::Nats.subscription_key(klass, method_name)
  end
end

#close_connectionObject



103
104
105
# File 'lib/protobuf/nats/client.rb', line 103

def close_connection
  # no-op (I think for now), the connection to server is persistent
end

#formatted_service_and_method_nameObject



231
232
233
234
235
# File 'lib/protobuf/nats/client.rb', line 231

def formatted_service_and_method_name
  klass = @options[:service]
  method_name = @options[:method]
  "#{klass}##{method_name}"
end

#loggerObject



35
36
37
# File 'lib/protobuf/nats/client.rb', line 35

def logger
  ::Protobuf::Logging.logger
end

#nack_backoff_intervalsObject



119
120
121
122
123
124
125
# File 'lib/protobuf/nats/client.rb', line 119

def nack_backoff_intervals
  @nack_backoff_intervals ||= if ::ENV.key?("PB_NATS_CLIENT_NACK_BACKOFF_INTERVALS")
    ::ENV["PB_NATS_CLIENT_NACK_BACKOFF_INTERVALS"].split(",").map(&:to_i)
  else
    [0, 1, 3, 5, 10]
  end
end

#nack_backoff_splayObject



127
128
129
130
131
132
133
# File 'lib/protobuf/nats/client.rb', line 127

def nack_backoff_splay
  @nack_backoff_splay ||= if nack_backoff_splay_limit > 0
    rand(nack_backoff_splay_limit)
  else
    0
  end
end

#nack_backoff_splay_limitObject



135
136
137
138
139
140
141
# File 'lib/protobuf/nats/client.rb', line 135

def nack_backoff_splay_limit
  @nack_backoff_splay_limit ||= if ::ENV.key?("PB_NATS_CLIENT_NACK_BACKOFF_SPLAY_LIMIT")
    ::ENV["PB_NATS_CLIENT_NACK_BACKOFF_SPLAY_LIMIT"].to_i
  else
    10
  end
end

#nats_request_with_two_responses(subject, data, opts) ⇒ Object



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
# File 'lib/protobuf/nats/client.rb', line 237

def nats_request_with_two_responses(subject, data, opts)
  # Wait for the ACK from the server
  ack_timeout = opts[:ack_timeout] || 5
  # Wait for the protobuf response
  timeout = opts[:timeout] || 60

  nats = Protobuf::Nats.client_nats_connection

  # Publish message with the reply topic pointed at the response muxer.
  req = RESPONSE_MUXER.new_request
  req.publish(subject, data)

  # Receive the first message
  begin
    first_message = req.next_message(ack_timeout)
    logger.debug { "received message with subject:#{first_message.subject}" } if logger.debug?
  rescue ::NATS::Timeout => e
    return :ack_timeout
  end

  # Check for a NACK
  return :nack if first_message.data == ::Protobuf::Nats::Messages::NACK

  # Receive the second message
  begin
    second_message = req.next_message(timeout)
  rescue ::NATS::Timeout
    # ignore to raise a repsonse timeout below
  end

  # NOTE: This might be nil, so be careful checking the data value
  second_message_data = second_message&.data

  # This should never happen, if it does, then return an :ack_timeout because something went wrong
  if first_message&.data == ::Protobuf::Nats::Messages::ACK &&
    second_message&.data == ::Protobuf::Nats::Messages::ACK
    logger.warn "received ACK/ACK message."
    return :ack_timeout
  end

  # Check messages
  response = case ::Protobuf::Nats::Messages::ACK
             when first_message&.data then second_message_data
             when second_message&.data then first_message&.data
             else return :ack_timeout
             end

  fail(::Protobuf::Nats::Errors::ResponseTimeout, formatted_service_and_method_name) unless response

  response
ensure
  # cleanup the token from the request map
  req.cleanup if req
end

#new_subscription_inboxObject



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/protobuf/nats/client.rb', line 77

def new_subscription_inbox
  nats = ::Protobuf::Nats.client_nats_connection
  inbox = nats.new_inbox
  sub = if use_subscription_pooling?
          nats.subscribe(inbox)
        else
          nats.subscribe(inbox, :max => 2)
        end

  SubscriptionInbox.new(sub, inbox)
end

#reconnect_delayObject



143
144
145
146
147
148
149
# File 'lib/protobuf/nats/client.rb', line 143

def reconnect_delay
  @reconnect_delay ||= if ::ENV.key?("PB_NATS_CLIENT_RECONNECT_DELAY")
    ::ENV["PB_NATS_CLIENT_RECONNECT_DELAY"].to_i
  else
    ack_timeout
  end
end

#response_muxerObject



39
40
41
# File 'lib/protobuf/nats/client.rb', line 39

def response_muxer
  RESPONSE_MUXER
end

#response_timeoutObject



151
152
153
154
155
156
157
# File 'lib/protobuf/nats/client.rb', line 151

def response_timeout
  @response_timeout ||= if ::ENV.key?("PB_NATS_CLIENT_RESPONSE_TIMEOUT")
    ::ENV["PB_NATS_CLIENT_RESPONSE_TIMEOUT"].to_i
  else
    60
  end
end

#send_requestObject



164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/protobuf/nats/client.rb', line 164

def send_request
  # This will ensure the client is started.
  ::Protobuf::Nats.start_client_nats_connection

  if use_subscription_pooling?
    available = self.class.subscription_pool.instance_variable_get("@available")
    ::ActiveSupport::Notifications.instrument "client.subscription_pool_available_size.protobuf-nats", available.length
  end

  ::ActiveSupport::Notifications.instrument "client.request_duration.protobuf-nats" do
    send_request_through_nats
  end
end

#send_request_through_natsObject



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
# File 'lib/protobuf/nats/client.rb', line 178

def send_request_through_nats
  retries ||= 3
  nack_retry ||= 0

  loop do
    setup_connection
    request_options = {:timeout => response_timeout, :ack_timeout => ack_timeout}
    @response_data = nats_request_with_two_responses(cached_subscription_key, @request_data, request_options)
    case @response_data
    when :ack_timeout
      ::ActiveSupport::Notifications.instrument "client.request_timeout.protobuf-nats"
      next if (retries -= 1) > 0
      raise ::Protobuf::Nats::Errors::RequestTimeout, formatted_service_and_method_name
    when :nack
      ::ActiveSupport::Notifications.instrument "client.request_nack.protobuf-nats"
      interval = nack_backoff_intervals[nack_retry]
      nack_retry += 1
      raise ::Protobuf::Nats::Errors::RequestTimeout, formatted_service_and_method_name if interval.nil?
      sleep((interval + nack_backoff_splay)/1000.0)
      next
    end

    break
  end

  parse_response
rescue ::Protobuf::Nats::Errors::IOException => error
  ::Protobuf::Nats.log_error(error)

  delay = reconnect_delay
  logger.warn "An IOException was raised. We are going to sleep for #{delay} seconds."
  sleep delay

  retry if (retries -= 1) > 0
  raise
end

#use_subscription_pooling?Boolean

Returns:

  • (Boolean)


159
160
161
162
# File 'lib/protobuf/nats/client.rb', line 159

def use_subscription_pooling?
  return @use_subscription_pooling unless @use_subscription_pooling.nil?
  @use_subscription_pooling = self.class.subscription_pool_size > 0
end

#with_subscriptionObject



89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/protobuf/nats/client.rb', line 89

def with_subscription
  return_value = nil

  if use_subscription_pooling?
    self.class.subscription_pool.with do |sub_inbox|
      return_value = yield sub_inbox
    end
  else
    return_value = yield new_subscription_inbox
  end

  return_value
end