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.



69
70
71
72
73
# File 'lib/smqueue/adapters/stomp.rb', line 69

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”)



163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/smqueue/adapters/stomp.rb', line 163

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



82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/smqueue/adapters/stomp.rb', line 82

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


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

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)


76
77
78
79
# File 'lib/smqueue/adapters/stomp.rb', line 76

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



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/smqueue/adapters/stomp.rb', line 115

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)


110
111
112
# File 'lib/smqueue/adapters/stomp.rb', line 110

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



100
101
102
103
104
105
106
107
# File 'lib/smqueue/adapters/stomp.rb', line 100

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


274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/smqueue/adapters/stomp.rb', line 274

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



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/smqueue/adapters/stomp.rb', line 139

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



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

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