From 77b1804eefe78a288611ea0de6dd8dfef8599220 Mon Sep 17 00:00:00 2001 From: Shivam Mishra Date: Mon, 21 Aug 2023 15:11:29 +0700 Subject: [PATCH] feat: create mutex application job --- app/jobs/mutex_application_job.rb | 35 +++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 app/jobs/mutex_application_job.rb diff --git a/app/jobs/mutex_application_job.rb b/app/jobs/mutex_application_job.rb new file mode 100644 index 000000000..16d681b34 --- /dev/null +++ b/app/jobs/mutex_application_job.rb @@ -0,0 +1,35 @@ +# MutexApplicationJob serves as a base class for jobs that require distributed locking mechanisms. +# It abstracts the locking logic using Redis and ensures that a block of code can be executed with +# mutual exclusion. +# +# The primary mechanism provided is the `with_lock` method, which accepts a key format and associated +# arguments. This method attempts to acquire a lock using the generated key, and if successful, it +# executes the provided block of code. If the lock cannot be acquired, it raises a LockAcquisitionError. +# +# To use this class, inherit from MutexApplicationJob and make use of the `with_lock` method in the +# `perform` method of the derived job class. +# +# Also see, retry mechanism here: https://edgeapi.rubyonrails.org/classes/ActiveJob/Exceptions/ClassMethods.html#method-i-retry_on +# +class MutexApplicationJob < ApplicationJob + class LockAcquisitionError < StandardError; end + + def with_lock(key_format, *args) + lock_key = format(key_format, *args) + lock_manager = Redis::LockManager.new + + if lock_manager.locked?(lock_key) + Rails.logger.error "[#{self.class.name}] Failed to acquire lock on attempt #{executions + 1}: #{lock_key}" + raise LockAcquisitionError, "Failed to acquire lock for key: #{lock_key}" + end + + begin + lock_manager.lock(lock_key) + Rails.logger.info "[#{self.class.name}] Acquired lock for: #{lock_key}" + yield + ensure + # Ensure that the lock is released even if there's an error in processing + lock_manager.unlock(lock_key) + end + end +end