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
# File 'lib/coatepec/worker/client.rb', line 32

def alive?
  return false unless @pid

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

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

Raises:



41
42
43
44
45
46
47
48
49
# File 'lib/coatepec/worker/client.rb', line 41

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



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

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