Class: Coatepec::Worker::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/coatepec/worker/client.rb

Overview

The parent-process handle to a spawned test worker: owns its pipes, sends NDJSON requests with a response timeout, and detects when the worker has died.

Defined Under Namespace

Classes: DisconnectedError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(project_root) ⇒ Client

Returns a new instance of Client.



17
18
19
20
# File 'lib/coatepec/worker/client.rb', line 17

def initialize(project_root)
  @project_root = project_root
  @next_id = 0
end

Class Method Details

.spawn(project_root) ⇒ Object



13
14
15
# File 'lib/coatepec/worker/client.rb', line 13

def self.spawn(project_root)
  new(project_root).tap(&:start)
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/coatepec/worker/client.rb', line 32

def alive?
  return false unless @pid

  # A dead-but-unreaped worker (crash, the OS reclaiming a long-idle
  # process, anything) is a zombie: Process.kill(0, pid) below would still
  # succeed against it, since it still holds a process-table entry. Reap it
  # here so staleness is detected instead of reported as "alive" forever --
  # nothing else calls Process.wait on this pid except #stop, which only
  # WorkerManager#restart_worker! reaches, and only once #alive? itself
  # already says false.
  _pid, status = Process.waitpid2(@pid, Process::WNOHANG)
  @pid = nil if status
  return false unless @pid

  Process.kill(0, @pid)
  true
rescue Errno::ESRCH, Errno::ECHILD
  false
end

#request(command, args, timeout: 30) ⇒ Object

Raises:



52
53
54
55
56
57
58
59
60
# File 'lib/coatepec/worker/client.rb', line 52

def request(command, args, timeout: 30)
  raise DisconnectedError, "Worker is not running" unless alive?

  id = (@next_id += 1)
  @protocol.write(id: id, command: command, args: args)
  message = read_response(id, timeout)

  message[:ok] ? message[:data] : raise_worker_error(message[:error])
end

#startObject



22
23
24
25
26
27
28
29
30
# File 'lib/coatepec/worker/client.rb', line 22

def start
  to_worker_r, @to_worker_write = IO.pipe
  @from_worker_read, from_worker_w = IO.pipe

  @pid = spawn_worker(to_worker_r, from_worker_w)
  to_worker_r.close
  from_worker_w.close
  @protocol = Protocol.new(input: @from_worker_read, output: @to_worker_write)
end

#stopObject



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/coatepec/worker/client.rb', line 62

def stop
  return unless @pid

  Process.kill("TERM", @pid)
  Process.wait(@pid)
rescue Errno::ESRCH, Errno::ECHILD
  nil
ensure
  [@to_worker_write, @from_worker_read].each { |io| io && !io.closed? && io.close }
  @pid = nil
end