lib/dynamoid_lockable.rb in dynamoid_lockable-1.0.0 vs lib/dynamoid_lockable.rb in dynamoid_lockable-1.1.0

- old
+ new

@@ -18,16 +18,17 @@ ensure_lockable_field(name) locked_until = Time.now + self.class.lock_config(name)[:duration] result = self.class - .lockable(name, locker_name: locker_name) - .upsert( - hash_key, - "#{name}_locked_until": locked_until, - "#{name}_locked_by": locker_name - ) + .lockable(name, locker_name: locker_name) + .upsert( + hash_key, + range_value, + "#{name}_locked_until": locked_until, + "#{name}_locked_by": locker_name, + ) raise CouldNotAcquireLock unless result # Prevents having to call reload, which we've seen take 20seconds # but still populates the value in memory, in case the code block @@ -40,11 +41,11 @@ def unlock(name) ensure_lockable_field(name) result = self.class.unlockable(name) - .upsert(hash_key, "#{name}_locked_until": nil) + .upsert(hash_key, range_value, "#{name}_locked_until": nil) raise CouldNotUnlock unless result true end @@ -66,13 +67,11 @@ ensure_lockable_field(name) config = self.class.lock_config(name) result = lock(name) - if config[:relock_every]&.positive? - relock_thread = create_relock_thread(name) - end + relock_thread = create_relock_thread(name) if config[:relock_every]&.positive? yield ensure relock_thread&.exit unlock(name) if result # Don't try to unlock if you didn't acquire lock @@ -100,22 +99,22 @@ lockable_fields[name.to_sym] end def locks_with(base_field, lock_for: DEFAULT_LOCK_TIME, relock_every: lock_for / 3) self.lockable_fields = lockable_fields.merge( - base_field.to_sym => { duration: lock_for, relock_every: relock_every } + base_field.to_sym => { duration: lock_for, relock_every: relock_every }, ) field "#{base_field}_locked_until".to_sym, :datetime field "#{base_field}_locked_by".to_sym, :string end def lockable(lock_name, locker_name: locking_name) ensure_lockable_field(lock_name) advanced_where do |r| - r.send(hash_key).exists? & ( + key_filter(r) & ( (r.send("#{lock_name}_locked_by") == locker_name) | !r.send("#{lock_name}_locked_until").exists? | (r.send("#{lock_name}_locked_until") < Time.now) ) end @@ -127,11 +126,19 @@ def unlockable(lock_name, locker_name: locking_name) ensure_lockable_field(lock_name) advanced_where do |r| - r.send(self.hash_key).exists? & + key_filter(r) & (r.send("#{lock_name}_locked_by") == locker_name) + end + end + + def key_filter(condition_builder) + if range_key + condition_builder.public_send(hash_key).exists? & condition_builder.public_send(range_key).exists? + else + condition_builder.public_send(hash_key).exists? end end end def self.included(other)