Class: Zold::SyncWallets

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/sync_wallets.rb

Overview

Synchronized collection of wallets

Instance Method Summary collapse

Constructor Details

#initialize(wallets, dir = Dir.tmpdir, timeout: 30, log: Log::Quiet.new) ⇒ SyncWallets

Returns a new instance of SyncWallets.



32
33
34
35
36
37
# File 'lib/zold/sync_wallets.rb', line 32

def initialize(wallets, dir = Dir.tmpdir, timeout: 30, log: Log::Quiet.new)
  @wallets = wallets
  @dir = dir
  @log = log
  @timeout = timeout
end

Instance Method Details

#allObject



47
48
49
# File 'lib/zold/sync_wallets.rb', line 47

def all
  @wallets.all
end

#find(id) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/zold/sync_wallets.rb', line 51

def find(id)
  @wallets.find(id) do |wallet|
    f = File.join(@dir, id)
    FileUtils.mkdir_p(File.dirname(f))
    File.open(f, File::RDWR | File::CREAT) do |lock|
      start = Time.now
      cycles = 0
      loop do
        break if lock.flock(File::LOCK_EX | File::LOCK_NB)
        sleep 0.1
        cycles += 1
        delay = (Time.now - start).round(2)
        if delay > @timeout
          raise "##{Process.pid}/#{Thread.current.name} can't get exclusive access to the wallet #{id} \
because of the lock at #{lock.path}, after #{delay}s of waiting: #{File.read(lock)}"
        end
        if (cycles % 20).zero? && delay > 10
          @log.info("##{Process.pid}/#{Thread.current.name} still waiting for \
exclusive access to #{id}, #{delay.round}s already: #{File.read(lock)}")
        end
      end
      File.write(lock, "##{Process.pid}/#{Thread.current.name}")
      yield wallet
    end
  end
end

#pathObject



43
44
45
# File 'lib/zold/sync_wallets.rb', line 43

def path
  @wallets.path
end

#to_sObject



39
40
41
# File 'lib/zold/sync_wallets.rb', line 39

def to_s
  @wallets.to_s
end