Class: RedlockForCollection::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/redlock_for_collection/collection.rb

Defined Under Namespace

Classes: LockPair

Constant Summary collapse

DEFAULT_TTL =
10_000
DEFAULT_MIN_VALIDITY =
5_000
DEFAULT_KEY_METHOD =
'key'.freeze
DEFAULT_KEY_PREFIX =
'prefix'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(objects, options, pool) ⇒ Collection

Returns a new instance of Collection.



12
13
14
15
16
17
18
# File 'lib/redlock_for_collection/collection.rb', line 12

def initialize(objects, options, pool)
  @objects = objects
  @options = options
  @pool    = pool

  init_options
end

Instance Attribute Details

#objectsObject (readonly)

Returns the value of attribute objects.



10
11
12
# File 'lib/redlock_for_collection/collection.rb', line 10

def objects
  @objects
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/redlock_for_collection/collection.rb', line 10

def options
  @options
end

#poolObject (readonly)

Returns the value of attribute pool.



10
11
12
# File 'lib/redlock_for_collection/collection.rb', line 10

def pool
  @pool
end

Instance Method Details

#lock(&block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/redlock_for_collection/collection.rb', line 20

def lock(&block)
  lock_pairs = []

  start_time = (Time.now.to_f * 1000).to_i
  @objects.each do |object|
    @pool.with do |redlock|
      lock_info = redlock.lock(build_key_for(object), @options[:ttl])
      lock_pairs << LockPair.new(object, lock_info)
    end
  end
  end_time = (Time.now.to_f * 1000).to_i

  separated_pairs = separate_expired_pairs(lock_pairs, end_time - start_time)

  begin
    separated_pairs[:valid].map(&:object)
    separated_pairs[:expired].map(&:object)
    block.yield(separated_pairs[:valid].map(&:object), separated_pairs[:expired].map(&:object))
  ensure
    # Release the all acquired locks
    unlock(lock_pairs)
  end
end