Skip to content

Commit

Permalink
add a prefix to job_id while locking
Browse files Browse the repository at this point in the history
  • Loading branch information
ankithads committed Aug 6, 2024
1 parent bfb8d83 commit a2afbb6
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/que/adapters/active_record_with_lock.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
module Que
module Adapters
class ActiveRecordWithLock < Que::Adapters::ActiveRecord
LOCK_PREFIX = ENV["QUE_LOCK_PREFIX"] || 1111 # this is a random number
def initialize(job_connection_pool:, lock_record:)
@job_connection_pool = job_connection_pool
@lock_record = lock_record
Expand Down Expand Up @@ -56,18 +57,20 @@ def cleanup!
end

def pg_try_advisory_lock?(job_id)
lock_variable = "#{LOCK_PREFIX}#{job_id}".to_i
lock_database_connection.execute(
"SELECT pg_try_advisory_lock(#{job_id})",
"SELECT pg_try_advisory_lock(#{lock_variable})",
).try(:first)&.fetch("pg_try_advisory_lock")
end

def unlock_job(job_id)
lock_variable = "#{LOCK_PREFIX}#{job_id}".to_i
# If for any reason the connection that is used to get this advisory lock
# is corrupted, the lock on this job_id would already be released when the
# connection holding the lock goes bad.
# Now, if a new connection tries to release the non existing lock this would just no op
# by returning false and return a warning "WARNING: you don't own a lock of type ExclusiveLock"
lock_database_connection.execute("SELECT pg_advisory_unlock(#{job_id})")
lock_database_connection.execute("SELECT pg_advisory_unlock(#{lock_variable})")
end
end
end
Expand Down

0 comments on commit a2afbb6

Please sign in to comment.