Class: STAN::Client

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/stan/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



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
# File 'lib/stan/client.rb', line 38

def initialize
  super

  # Connection to NATS, either owned or borrowed
  @nats = nil
  @borrowed_nats_connection = false

  # STAN subscriptions map
  @sub_map = {}

  # Publish Ack map (guid => ack)
  @pub_ack_map = {}
  @pending_pub_acks = nil

  # Cluster to which we are connecting
  @cluster_id = nil
  @client_id = nil

  # Connect options
  @options = {}

  # NATS Streaming subjects

  # Inbox subscription for periodical heartbeat messages
  @hb_inbox = nil
  @hb_inbox_sid = nil

  # Subscription for processing received acks from the server
  @ack_subject = nil
  @ack_subject_sid = nil

  # Publish prefix set by stan to which we append our subject on publish.
  @pub_prefix        = nil
  @sub_req_subject   = nil
  @unsub_req_subject = nil
  @close_req_subject = nil
  @sub_close_req_subject = nil

  # For initial connect request to discover subjects used by
  # the streaming server.
  @discover_subject = nil
end

Instance Attribute Details

#client_idObject (readonly)

Returns the value of attribute client_id.



36
37
38
# File 'lib/stan/client.rb', line 36

def client_id
  @client_id
end

#natsObject (readonly)

Returns the value of attribute nats.



36
37
38
# File 'lib/stan/client.rb', line 36

def nats
  @nats
end

#optionsObject (readonly)

Returns the value of attribute options.



36
37
38
# File 'lib/stan/client.rb', line 36

def options
  @options
end

#pending_pub_acksObject (readonly)

Returns the value of attribute pending_pub_acks.



36
37
38
# File 'lib/stan/client.rb', line 36

def pending_pub_acks
  @pending_pub_acks
end

#sub_close_req_subjectObject (readonly)

Returns the value of attribute sub_close_req_subject.



36
37
38
# File 'lib/stan/client.rb', line 36

def sub_close_req_subject
  @sub_close_req_subject
end

#sub_mapObject (readonly)

Returns the value of attribute sub_map.



36
37
38
# File 'lib/stan/client.rb', line 36

def sub_map
  @sub_map
end

#unsub_req_subjectObject (readonly)

Returns the value of attribute unsub_req_subject.



36
37
38
# File 'lib/stan/client.rb', line 36

def unsub_req_subject
  @unsub_req_subject
end

Instance Method Details

#ack(msg) ⇒ Object

Ack takes a received message and publishes an ack manually



314
315
316
317
318
319
320
321
322
323
# File 'lib/stan/client.rb', line 314

def ack(msg)
  return unless msg.sub
  msg.sub.synchronize do
    ack_proto = STAN::Protocol::Ack.new({
      subject: msg.proto.subject,
      sequence: msg.proto.sequence
    }).to_proto
    nats.publish(msg.sub.ack_inbox, ack_proto)
  end
end

#closeObject

Close wraps us the session with the NATS Streaming server



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
# File 'lib/stan/client.rb', line 281

def close
  req = STAN::Protocol::CloseRequest.new(clientID: @client_id)
  raw = nats.request(@close_req_subject, req.to_proto)

  resp = STAN::Protocol::CloseResponse.decode(raw.data)
  unless resp.error.empty?
    raise Error.new(resp.error)
  end

  # TODO: If connection to nats was borrowed then we should
  # unsubscribe from all topics from STAN.  If not borrowed
  # and we own the connection, then we just close.
  begin
    # Remove all present subscriptions
    @sub_map.each_pair do |_, sub|
      nats.unsubscribe(sub.sid)
    end

    # Finally, remove the core subscriptions for STAN
    nats.unsubscribe(@hb_inbox_sid)
    nats.unsubscribe(@ack_subject_sid)
  rescue => e
    # TODO: Async error handling
  ensure
    if @borrowed_nats_connection
      @nats = nil
    else
      @nats.close
    end
  end
end

#connect(cluster_id, client_id, opts = {}, &blk) ⇒ Object

Plugs into a NATS Streaming cluster, establishing a connection to NATS in case there is not one available to be borrowed.

Raises:



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
# File 'lib/stan/client.rb', line 83

def connect(cluster_id, client_id, opts={}, &blk)
  @cluster_id = cluster_id
  @client_id  = client_id
  @options    = opts

  # Defaults
  @options[:connect_timeout] ||= DEFAULT_CONNECT_TIMEOUT
  @options[:max_pub_acks_inflight] ||= DEFAULT_MAX_PUB_ACKS_INFLIGHT

  # Buffered queue for controlling inflight published acks
  @pending_pub_acks = SizedQueue.new(options[:max_pub_acks_inflight])

  # Prepare connect discovery request
  @discover_subject = "#{DEFAULT_DISCOVER_SUBJECT}.#{@cluster_id}".freeze

  # Prepare delivered msgs acks processing subscription
  @ack_subject = "#{DEFAULT_ACKS_SUBJECT}.#{STAN.create_guid}".freeze

  if @nats.nil?
    case options[:nats]
    when Hash
      # Custom NATS options in case borrowed connection not present
      # can be passed to establish a connection and have stan client
      # owning it.
      @nats = NATS::IO::Client.new
      nats.connect(options[:nats])
    when NATS::IO::Client
      @nats = options[:nats]
      @borrowed_nats_connection = true
    else
      # Try to connect with NATS defaults
      @nats = NATS::IO::Client.new
      nats.connect(servers: ["nats://127.0.0.1:4222"])
    end
  end

  # If no connection to NATS present at this point then bail already
  raise ConnectError.new("stan: invalid connection to nats") unless @nats

  # Heartbeat subscription
  @hb_inbox = (STAN.create_inbox).freeze

  # Setup acks and heartbeats processing callbacks
  @hb_inbox_sid    = nats.subscribe(@hb_inbox)    { |raw| process_heartbeats(raw) }
  @ack_subject_sid = nats.subscribe(@ack_subject) { |raw| process_ack(raw) }
  nats.flush

  # Initial connect request to discover subjects to be used
  # for communicating with STAN.
  req = STAN::Protocol::ConnectRequest.new({
    clientID: @client_id,
    heartbeatInbox: @hb_inbox
  })

  # TODO: Check for error and bail if required
  raw = nats.request(@discover_subject, req.to_proto, timeout: options[:connect_timeout])
  resp = STAN::Protocol::ConnectResponse.decode(raw.data)
  @pub_prefix = resp.pubPrefix.freeze
  @sub_req_subject = resp.subRequests.freeze
  @unsub_req_subject = resp.unsubRequests.freeze
  @close_req_subject = resp.closeRequests.freeze
  @sub_close_req_subject = resp.subCloseRequests.freeze

  # If callback given then we send a close request on exit
  # and wrap up session to STAN.
  if blk
    blk.call(self)

    # Close session to the STAN cluster
    close
  end
end

#publish(subject, payload, opts = {}, &blk) ⇒ Object

Publish will publish to the cluster and wait for an ack



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
# File 'lib/stan/client.rb', line 157

def publish(subject, payload, opts={}, &blk)
  stan_subject = "#{@pub_prefix}.#{subject}"
  future = nil
  guid = STAN.create_guid

  pe = STAN::Protocol::PubMsg.new({
    clientID: @client_id,
    guid: guid,
    subject: subject,
    data: payload
  })

  # Use buffered queue to control number of outstanding acks
  @pending_pub_acks << :ack

  if blk
    # Asynchronously handled if block given
    synchronize do
      # Map ack to guid
      @pub_ack_map[guid] = proc do |ack|
        # If block is given, handle the result asynchronously
        error = ack.error.empty? ? nil : Error.new(ack.error)
        case blk.arity
        when 0 then blk.call
        when 1 then blk.call(ack.guid)
        when 2 then blk.call(ack.guid, error)
        end

        @pub_ack_map.delete(ack.guid)
      end

      nats.publish(stan_subject, pe.to_proto, @ack_subject)
    end
  else
    # No block means waiting for response before giving back control
    future = new_cond
    opts[:timeout] ||= DEFAULT_ACK_WAIT

    synchronize do
      # Map ack to guid
      ack_response = nil

      # FIXME: Maybe use fiber instead?
      @pub_ack_map[guid] = proc do |ack|
        # Capture the ack response
        ack_response = ack
        future.signal
      end

      # Send publish request and wait for the ack response
      nats.publish(stan_subject, pe.to_proto, @ack_subject)
      start_time = NATS::MonotonicTime.now
      future.wait(opts[:timeout])
      end_time = NATS::MonotonicTime.now
      if (end_time - start_time) > opts[:timeout]
        # Remove ack
        @pub_ack_map.delete(guid)
        raise TimeoutError.new("stan: timeout")
      end

      # Remove ack
      @pub_ack_map.delete(guid)
      return guid
    end
  end
  # TODO: Loop for processing of expired acks
end

#subscribe(subject, opts = {}, &cb) ⇒ Object

Create subscription which dispatches messages to callback asynchronously



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
# File 'lib/stan/client.rb', line 226

def subscribe(subject, opts={}, &cb)
  sub_options = {}
  sub_options.merge!(opts)
  sub_options[:ack_wait] ||= DEFAULT_ACK_WAIT
  sub_options[:max_inflight] ||= DEFAULT_MAX_INFLIGHT
  sub_options[:stan] = self

  sub = Subscription.new(subject, sub_options, cb)
  sub.extend(MonitorMixin)
  synchronize { @sub_map[sub.inbox] = sub }

  # Hold lock throughout
  sub.synchronize do
    # Listen for actual messages
    sid = nats.subscribe(sub.inbox) { |raw, reply, subject| process_msg(raw, reply, subject) }
    sub.sid = sid
    nats.flush

    # Create the subscription request announcing the inbox on which
    # we have made the NATS subscription for processing messages.
    # First, we normalize customized subscription options before
    # encoding to protobuf.
    sub_opts = normalize_sub_req_params(sub_options)

    # Set STAN subject and NATS inbox where we will be awaiting
    # for the messages to be delivered.
    sub_opts[:subject] = subject
    sub_opts[:inbox] = sub.inbox

    sr = STAN::Protocol::SubscriptionRequest.new(sub_opts)
    reply = nil
    response = nil
    begin
      reply = nats.request(@sub_req_subject, sr.to_proto, timeout: options[:connect_timeout])
      response = STAN::Protocol::SubscriptionResponse.decode(reply.data)
    rescue NATS::IO::Timeout, Google::Protobuf::ParseError => e
      # FIXME: Error handling on unsubscribe
      nats.unsubscribe(sub.sid)
      raise e
    end

    unless response.error.empty?
      # FIXME: Error handling on unsubscribe
      nats.unsubscribe(sub.sid)
      raise Error.new(response.error)
    end

    # Capture ack inbox for the subscription
    sub.ack_inbox = response.ackInbox.freeze

    return sub
  end
end