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.



38
39
40
41
42
43
44
45
46
# File 'lib/bootsnap/cli/worker_pool.rb', line 38

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.



36
37
38
# File 'lib/bootsnap/cli/worker_pool.rb', line 36

def pid
  @pid
end

#to_ioObject (readonly)

Returns the value of attribute to_io.



36
37
38
# File 'lib/bootsnap/cli/worker_pool.rb', line 36

def to_io
  @to_io
end

Instance Method Details

#closeObject



58
59
60
# File 'lib/bootsnap/cli/worker_pool.rb', line 58

def close
  to_io.close
end

#spawnObject



73
74
75
76
77
78
79
80
81
# File 'lib/bootsnap/cli/worker_pool.rb', line 73

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

#work_loopObject



62
63
64
65
66
67
68
69
70
71
# File 'lib/bootsnap/cli/worker_pool.rb', line 62

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



48
49
50
51
52
53
54
55
56
# File 'lib/bootsnap/cli/worker_pool.rb', line 48

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