Class: RubyEventStore::Outbox::Repository::Lock

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/ruby_event_store/outbox/repository.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.obtain(fetch_specification, process_uuid, clock:) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ruby_event_store/outbox/repository.rb', line 35

def self.obtain(fetch_specification, process_uuid, clock:)
  transaction do
    l = get_lock_record(fetch_specification)

    if l.recently_locked?(clock: clock)
      :taken
    else
      l.update!(locked_by: process_uuid, locked_at: clock.now)
      l
    end
  end
rescue ::ActiveRecord::Deadlocked
  :deadlocked
rescue ::ActiveRecord::LockWaitTimeout
  :lock_timeout
end

.release(fetch_specification, process_uuid) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/ruby_event_store/outbox/repository.rb', line 69

def self.release(fetch_specification, process_uuid)
  transaction do
    l = get_lock_record(fetch_specification)
    if !l.locked_by?(process_uuid)
      :not_taken_by_this_process
    else
      l.update!(locked_by: nil, locked_at: nil)
      :ok
    end
  end
rescue ::ActiveRecord::Deadlocked
  :deadlocked
rescue ::ActiveRecord::LockWaitTimeout
  :lock_timeout
end

Instance Method Details

#fetch_specificationObject



93
94
95
# File 'lib/ruby_event_store/outbox/repository.rb', line 93

def fetch_specification
  FetchSpecification.new(format, split_key)
end

#locked_by?(process_uuid) ⇒ Boolean

Returns:

  • (Boolean)


85
86
87
# File 'lib/ruby_event_store/outbox/repository.rb', line 85

def locked_by?(process_uuid)
  locked_by.eql?(process_uuid)
end

#recently_locked?(clock:) ⇒ Boolean

Returns:

  • (Boolean)


89
90
91
# File 'lib/ruby_event_store/outbox/repository.rb', line 89

def recently_locked?(clock:)
  locked_by && locked_at > RECENTLY_LOCKED_DURATION.ago(clock.now)
end

#refresh(clock:) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/ruby_event_store/outbox/repository.rb', line 52

def refresh(clock:)
  transaction do
    current_process_uuid = locked_by
    lock!
    if locked_by == current_process_uuid
      update!(locked_at: clock.now)
      :ok
    else
      :stolen
    end
  end
rescue ::ActiveRecord::Deadlocked
  :deadlocked
rescue ::ActiveRecord::LockWaitTimeout
  :lock_timeout
end