Skip to content

Instantly share code, notes, and snippets.

@mberman84
Created June 11, 2016 18:21
Show Gist options
  • Save mberman84/a09032d0e25be674e1bd78491fa562b6 to your computer and use it in GitHub Desktop.
Save mberman84/a09032d0e25be674e1bd78491fa562b6 to your computer and use it in GitHub Desktop.
class AwayMessagesWorker
include Sidekiq::Worker
include Sidetiq::Schedulable
sidekiq_options retry: false
recurrence { secondly(10) }
def perform
redis_away_lock_key = 'away_messaging'
lock_manager = Redlock::Client.new([RED])
# will lock away message sending for 5 seconds
lock_manager.lock(redis_away_lock_key, 5000) do |locked|
if locked
# if it locks, there wasn't a lock already in place, which means it's good to go
Rails.logger.info 'AWAY_MESSAGE: has been locked, sending away messages'
RED.hkeys('away_messages').each do |key|
customer_id = key
Rails.logger.info "AWAY_MESSAGE: found customer with id #{customer_id}"
RED.hdel('away_messages', key)
customer = Customer.find(customer_id)
next unless !customer.received_away_message? && customer.allowed_country_for_sending? && customer.subscribed?
company = customer.company
parsed_message_text = Message.replace_variables(company.away_message.text, customer)
message_params = {
type: customer.last_channel,
customer_id: customer.id,
user_id: company.admin.id,
company_id: company.id,
full_text: parsed_message_text,
react_uuid: SecureRandom.urlsafe_base64(10),
viewed: true,
away_message: true,
via_auto_reply: false,
direction: 'sent'
}
message_params[:facebook_conversation_id] = customer.fb_conversation_id if customer.last_channel_facebook?
Rails.logger.info "AWAY_MESSAGE: sending away message to #{customer.id}"
RED.setex("away_sent_for_#{customer.id}", 3_600, true)
DispatchServiceWorker.perform_async(message_params)
end
else
# there was already a lock in place, skip this away message worker
Rails.logger.info 'AWAY_MESSAGE: was already locked, skipping this job'
end
end
binding.pry
lock_manager.unlock(locked)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment