Class: Zold::SpreadEntrance

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

Overview

The entrance

Instance Method Summary collapse

Constructor Details

#initialize(entrance, wallets, remotes, address, log: Log::NULL, ignore_score_weakeness: false) ⇒ SpreadEntrance

Returns a new instance of SpreadEntrance.



43
44
45
46
47
48
49
50
51
# File 'lib/zold/node/spread_entrance.rb', line 43

def initialize(entrance, wallets, remotes, address, log: Log::NULL, ignore_score_weakeness: false)
  @entrance = entrance
  @wallets = wallets
  @remotes = remotes
  @address = address
  @log = log
  @ignore_score_weakeness = ignore_score_weakeness
  @mutex = Mutex.new
end

Instance Method Details

#push(id, body) ⇒ Object

This method is thread-safe



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/zold/node/spread_entrance.rb', line 95

def push(id, body)
  mods = @entrance.push(id, body)
  return mods if @remotes.all.empty?
  (mods + [id]).each do |m|
    next if @seen.include?(m)
    @mutex.synchronize { @seen << m }
    @modified.push(m)
    @log.debug("Spread-push scheduled for #{m}, queue size is #{@modified.size}")
  end
  mods
end

#startObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/zold/node/spread_entrance.rb', line 60

def start
  raise 'Block must be given to start()' unless block_given?
  @entrance.start do
    @seen = Set.new
    @modified = Queue.new
    @push = Thread.start do
      Endless.new('push', log: @log).run do
        id = @modified.pop
        if @remotes.all.empty?
          @log.info("There are no remotes, won't spread #{id}")
        elsif @wallets.acq(id) { |w| Tax.new(w).in_debt? }
          @log.info("The wallet #{id} is in debt, won't spread")
        else
          Thread.current.thread_variable_set(:wallet, id.to_s)
          Push.new(wallets: @wallets, remotes: @remotes, log: @log).run(
            ['push', "--ignore-node=#{@address}", id.to_s] +
            (@ignore_score_weakeness ? ['--ignore-score-weakness'] : [])
          )
        end
        @mutex.synchronize { @seen.delete(id) }
      end
    end
    begin
      yield(self)
    ensure
      @log.info('Waiting for spread entrance to finish...')
      @modified.clear
      @push.kill
      @push.join
      @log.info('Spread entrance finished, thread killed')
    end
  end
end

#to_jsonObject



53
54
55
56
57
58
# File 'lib/zold/node/spread_entrance.rb', line 53

def to_json
  @entrance.to_json.merge(
    'modified': @modified.size,
    'push': @push.status
  )
end