Class: SMQueue::StompAdapter

Inherits:
Adapter show all
Defined in:
lib/smqueue/adapters/stomp.rb

Defined Under Namespace

Classes: Configuration

Instance Method Summary collapse

Methods inherited from Adapter

#close, create, #open

Methods inherited from Doodle

#to_hash

Constructor Details

#initialize(*args, &block) ⇒ StompAdapter

Returns a new instance of StompAdapter.



133
134
135
136
137
# File 'lib/smqueue/adapters/stomp.rb', line 133

def initialize(*args, &block)
  super
  restore_remembered_messages
  SMQueue.dbg { [:seen_messages, seen_messages].inspect }
end

Instance Method Details

#ack(subscription_headers, message) ⇒ Object

acknowledge message (if headers == “client”)



227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/smqueue/adapters/stomp.rb', line 227

def ack(subscription_headers, message)
  #p [:ack, message.headers["message-id"]]
  if message.headers["message-id"].to_s.strip != "" && subscription_headers["ack"].to_s == "client"
    SMQueue.dbg { [:smqueue, :ack, :message, message].inspect }
    connection.ack message.headers["message-id"], { }
  else
    SMQueue.dbg { [:smqueue, :ack, :not_acknowledging, message].inspect }
  end
  if ENV['PAUSE_SMQUEUE']
    $stderr.print "press enter to continue> "
    $stderr.flush
    $stdin.gets
  end
end

#connect(*args, &block) ⇒ Object

connect to message broker



146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/smqueue/adapters/stomp.rb', line 146

def connect(*args, &block)
  self.connection = RStomp::Connection.open(configuration.to_hash)   
  # If the connection has swapped hosts, then swap out primary and secondary
  if connection.current_host != configuration.host
    configuration.secondary_host = configuration.host
    configuration.host = connection.current_host
  end

  # If the connection has swapped ports, then swap out primary and secondary
  if connection.current_port != configuration.port
    configuration.secondary_port = configuration.port
    configuration.port = connection.current_port
  end
end

#get(headers = {}, &block) ⇒ Object

get message from queue

  • if block supplied, loop forever and yield(message) for each message received

default headers are:

:ack               => "client"
:client_id         => configuration.client_id
:subscription_name => configuration.subscription_name


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
# File 'lib/smqueue/adapters/stomp.rb', line 250

def get(headers = {}, &block)
  self.connect
  SMQueue.dbg { [:smqueue, :get, headers].inspect }
  subscription_headers = {"ack" => "client", "activemq.prefetchSize" => 1 }
  if client_id = configuration.client_id
    subscription_headers["client_id"] = client_id
  end
  if sub_name = configuration.subscription_name
    subscription_headers["subscription_name"] = sub_name
  end
  # if a client_id is supplied, then user wants a durable subscription
  # N.B. client_id must be unique for broker
  subscription_headers.update(headers)
  #p [:subscription_headers_before, subscription_headers]
  subscription_headers = normalize_keys(subscription_headers)
  if configuration.durable and client_id = configuration.client_id || subscription_headers["client_id"]
    subscription_name = configuration.subscription_name || subscription_headers["subscription_name"] || client_id
    # activemq only
    subscription_headers["activemq.subscriptionName"] = subscription_name
    # JMS
    subscription_headers["durable-subscriber-name"] = subscription_name
  end
  #p [:subscription_headers_after, subscription_headers]
  
  destination = configuration.name
  SMQueue.dbg { [:smqueue, :get, :subscribing, destination, :subscription_headers, subscription_headers].inspect }
  connection.subscribe destination, subscription_headers
  message = nil
  SMQueue.dbg { [:smqueue, :get, :subscription_headers, subscription_headers].inspect }
  begin
    # TODO: refactor this
    if block_given?
      SMQueue.dbg { [:smqueue, :get, :block_given].inspect }
      # todo: change to @running - (and set to false from exception handler)
      # also should check to see if anything left to receive on connection before bailing out
      while true
        SMQueue.dbg { [:smqueue, :get, :receive].inspect }
        # block until message ready
        message = connection.receive
        SMQueue.dbg { [:smqueue, :get, :received, message].inspect }
        case message.command
        when "ERROR"
          SMQueue.dbg { [:smqueue, :get, :ERROR, message].inspect }
        when "RECEIPT"
          SMQueue.dbg { [:smqueue, :get, :RECEIPT, message].inspect }
        else
          SMQueue.dbg { [:smqueue, :get, :yielding].inspect }
          if !message_seen?(message.headers["message-id"])
            yield(message)
          end
          SMQueue.dbg { [:smqueue, :get, :message_seen, message.headers["message-id"]].inspect }
          message_seen message.headers["message-id"]
          SMQueue.dbg { [:smqueue, :get, :returned_from_yield_now_calling_ack].inspect }
          ack(subscription_headers, message)
          SMQueue.dbg { [:smqueue, :get, :returned_from_ack].inspect }
        end
      end
    else
      SMQueue.dbg { [:smqueue, :get, :single_shot].inspect }
      message = connection.receive
      SMQueue.dbg { [:smqueue, :get, :received, message].inspect }
      if !(message.command == "ERROR" or message.command == "RECEIPT")
        SMQueue.dbg { [:smqueue, :get, :message_seen, message.headers["message-id"]].inspect }
        message_seen message.headers["message-id"]
        SMQueue.dbg { [:smqueue, :get, :ack, message].inspect }
        ack(subscription_headers, message)
        SMQueue.dbg { [:smqueue, :get, :returned_from_ack].inspect }
      end
    end
  rescue Object => e
    SMQueue.dbg { [:smqueue, :get, :exception, e].inspect }
    handle_error e, "Exception in SMQueue#get: #{e.message}", caller
  ensure
    SMQueue.dbg { [:smqueue, :get, :ensure].inspect }
    SMQueue.dbg { [:smqueue, :unsubscribe, destination, subscription_headers].inspect }
    connection.unsubscribe destination, subscription_headers
    SMQueue.dbg { [:smqueue, :disconnect].inspect }
    connection.disconnect
  end
  SMQueue.dbg { [:smqueue, :get, :return].inspect }
  message
end

#handle_error(exception_class, error_message, caller) ⇒ Object

handle an error

Raises:

  • (exception_class)


140
141
142
143
# File 'lib/smqueue/adapters/stomp.rb', line 140

def handle_error(exception_class, error_message, caller)
  #configuration.logger.warn error_message
  raise exception_class, error_message, caller
end

#message_seen(message_id) ⇒ Object

remember the message_id



179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/smqueue/adapters/stomp.rb', line 179

def message_seen(message_id)
  message_id = message_id.to_s.strip
  if message_id != ""
    self.seen_messages << message_id
    SMQueue.dbg { [:smqueue, :ack, :message_seen, message_id].inspect }
    if self.seen_messages.size > self.seen_message_count
      self.seen_messages.shift
    end
    store_remembered_messages
  else
    SMQueue.dbg { [:smqueue, :ack, :message_seen, message_id].inspect }
  end
end

#message_seen?(message_id) ⇒ Boolean

true if the message with this message_id has already been seen

Returns:

  • (Boolean)


174
175
176
# File 'lib/smqueue/adapters/stomp.rb', line 174

def message_seen?(message_id)
  self.seen_messages.include?(message_id)
end

#normalize_keys(hash, method = :to_s) ⇒ Object

normalize hash keys (top level only)

  • normalizes keys to strings by default

  • optionally pass in name of method to use (e.g. :to_sym) to normalize keys



164
165
166
167
168
169
170
171
# File 'lib/smqueue/adapters/stomp.rb', line 164

def normalize_keys(hash, method = :to_s)
  hash = hash.dup
  hash.keys.each do |k|
    normalized_key = k.respond_to?(method) ? k.send(method) : k
    hash[normalized_key] = hash.delete(k)
  end
  hash
end

#put(body, headers = { }) ⇒ Object

put a message on the queue default headers are:

:persistent => true
:ack        => "auto"
:expires    => configuration.expires


338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/smqueue/adapters/stomp.rb', line 338

def put(body, headers = { })
  SMQueue.dbg { [:smqueue, :put, body, headers].inspect }
  begin
    self.connect
    headers = {:persistent => true, :ack => "auto", :expires => SMQueue.calc_expiry_time(configuration.expires) }.merge(headers)
    destination = configuration.name
    SMQueue.dbg { [:smqueue, :send, body, headers].inspect }
    connection.send destination, body, headers
  rescue Exception => e
    SMQueue.dbg { [:smqueue, :exception, e].inspect }
    handle_error e, "Exception in SMQueue#put - #{e.message}", caller
    #connection.disconnect
  ensure
    connection.disconnect
  end
end

#restore_remembered_messagesObject

reload remembered message ids from a yaml file



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/smqueue/adapters/stomp.rb', line 203

def restore_remembered_messages
  if configuration.single_delivery
    yaml = default_yaml = "--- []"
    begin
      File.open(seen_messages_file, 'r') do |file|
        yaml = file.read
      end
    rescue Object
      yaml = default_yaml
    end
    buffer = []
    begin
      buffer = YAML.load(yaml)
      if !buffer.kind_of?(Array) or !buffer.all?{ |x| x.kind_of?(String)}
        raise Exception, "Invalid seen_messages.yml file"
      end
    rescue Object
      buffer = []
    end
    self.seen_messages = buffer
  end
end

#store_remembered_messagesObject

store the remembered message ids in a yaml file



194
195
196
197
198
199
200
# File 'lib/smqueue/adapters/stomp.rb', line 194

def store_remembered_messages
  if configuration.single_delivery
    File.open(seen_messages_file, 'w') do |file|
      file.write seen_messages.to_yaml
    end
  end
end