lib/propono/services/publisher.rb in propono-1.2.0 vs lib/propono/services/publisher.rb in propono-1.3.0

- old
+ new

@@ -9,11 +9,11 @@ def self.publish(topic_id, message, options = {}) new(topic_id, message, options).publish end - attr_reader :topic_id, :message, :protocol, :id + attr_reader :topic_id, :message, :protocol, :id, :async def initialize(topic_id, message, options = {}) raise PublisherError.new("Topic is nil") if topic_id.nil? raise PublisherError.new("Message is nil") if message.nil? @@ -22,33 +22,40 @@ @topic_id = topic_id @message = message @protocol = options.fetch(:protocol, :sns).to_sym @id = SecureRandom.hex(3) @id = "#{options[:id]}-#{@id}" if options[:id] + @async = options.fetch(:async, true) end def publish Propono.config.logger.info "Propono [#{id}]: Publishing #{message} to #{topic_id} via #{protocol}" send("publish_via_#{protocol}") end private def publish_via_sns - Thread.new do - begin - topic = TopicCreator.find_or_create(topic_id) - rescue => e - Propono.config.logger.error "Propono [#{id}]: Failed to create topic #{topic_id}: #{e}" - raise - end + async ? publish_via_sns_asyncronously : publish_via_sns_syncronously + end - begin - sns.publish(topic.arn, body.to_json) - rescue => e - Propono.config.logger.error "Propono [#{id}]: Failed to send via sns: #{e}" - raise - end + def publish_via_sns_asyncronously + Thread.new { publish_via_sns_syncronously } + end + + def publish_via_sns_syncronously + begin + topic = TopicCreator.find_or_create(topic_id) + rescue => e + Propono.config.logger.error "Propono [#{id}]: Failed to create topic #{topic_id}: #{e}" + raise + end + + begin + sns.publish(topic.arn, body.to_json) + rescue => e + Propono.config.logger.error "Propono [#{id}]: Failed to send via sns: #{e}" + raise end end def publish_via_udp payload = body.merge(topic: topic_id).to_json