Class: Bootsnap::CLI::WorkerPool::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/bootsnap/cli/worker_pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(jobs) ⇒ Worker

Returns a new instance of Worker.



110
111
112
113
114
115
116
117
118
# File 'lib/bootsnap/cli/worker_pool.rb', line 110

def initialize(jobs)
  @jobs = jobs
  @pipe_out, @to_io = IO.pipe(binmode: true)
  # Set the writer encoding to binary since IO.pipe only sets it for the reader.
  # https://github.com/rails/rails/issues/16514#issuecomment-52313290
  @to_io.set_encoding(Encoding::BINARY)

  @pid = nil
end

Instance Attribute Details

#pidObject (readonly)

Returns the value of attribute pid.



108
109
110
# File 'lib/bootsnap/cli/worker_pool.rb', line 108

def pid
  @pid
end

#to_ioObject (readonly)

Returns the value of attribute to_io.



108
109
110
# File 'lib/bootsnap/cli/worker_pool.rb', line 108

def to_io
  @to_io
end

Instance Method Details

#closeObject



130
131
132
# File 'lib/bootsnap/cli/worker_pool.rb', line 130

def close
  to_io.close
end

#spawnObject



145
146
147
148
149
150
151
152
153
# File 'lib/bootsnap/cli/worker_pool.rb', line 145

def spawn
  @pid = Process.fork do
    to_io.close
    work_loop
    exit!(0)
  end
  @pipe_out.close
  true
end

#work_loopObject



134
135
136
137
138
139
140
141
142
143
# File 'lib/bootsnap/cli/worker_pool.rb', line 134

def work_loop
  loop do
    job, *args = Marshal.load(@pipe_out)
    return if job == :exit

    @jobs.fetch(job).call(*args)
  end
rescue IOError
  nil
end

#write(message, block: true) ⇒ Object



120
121
122
123
124
125
126
127
128
# File 'lib/bootsnap/cli/worker_pool.rb', line 120

def write(message, block: true)
  payload = Marshal.dump(message)
  if block
    to_io.write(payload)
    true
  else
    to_io.write_nonblock(payload, exception: false) != :wait_writable
  end
end