refactor: use MutexApplicationJob

This commit is contained in:
Shivam Mishra
2023-08-23 11:59:24 +07:00
parent 77b1804eef
commit 79a76bc9df
2 changed files with 7 additions and 17 deletions
+2 -16
View File
@@ -1,24 +1,10 @@
class SendOnSlackJob < ApplicationJob
class LockAcquisitionError < StandardError; end
class SendOnSlackJob < MutexApplicationJob
queue_as :medium
retry_on LockAcquisitionError, wait: 3.seconds, attempts: 5
def perform(message, hook)
lock_key = format(::Redis::Alfred::SLACK_MESSAGE_MUTEX, sender_id: message.sender_id, reference_id: hook.reference_id)
lock_manager = Redis::LockManager.new
if lock_manager.locked?(lock_key)
Rails.logger.error "[SendOnSlackJob] Failed to acquire lock on attempt #{executions + 1}: #{lock_key}"
raise LockAcquisitionError, "Failed to acquire lock for key: #{lock_key}"
end
begin
Rails.logger.info "[SendOnSlackJob] Acquired lock for: #{lock_key}"
with_lock(::Redis::Alfred::SLACK_MESSAGE_MUTEX, sender_id: message.sender_id, reference_id: hook.reference_id) do
Integrations::Slack::SendOnSlackService.new(message: message, hook: hook).perform
ensure
# Ensure that the lock is released even if there's an error in processing
lock_manager.unlock(lock_key)
end
end
end
+5 -1
View File
@@ -1,8 +1,12 @@
class Webhooks::FacebookEventsJob < ApplicationJob
queue_as :default
retry_on LockAcquisitionError, wait: 2.seconds, attempts: 5
def perform(message)
response = ::Integrations::Facebook::MessageParser.new(message)
::Integrations::Facebook::MessageCreator.new(response).perform
with_lock(::Redis::Alfred::FACEBOOK_MESSAGE_MUTEX, sender_id: response.sender_id, recipient_id: response.recipient_id) do
::Integrations::Facebook::MessageCreator.new(response).perform
end
end
end