Class: ConsoleIpc::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/console_ipc/connection.rb

Constant Summary collapse

DEFAULT_SOCKET_PATH =
'tmp/console_ipc.sock'
STOP_WAIT_TIMEOUT_SECONDS =
5

Class Method Summary collapse

Class Method Details

.execute(code, socket_path: self.socket_path) ⇒ Object



27
28
29
# File 'lib/console_ipc/connection.rb', line 27

def self.execute(code, socket_path: self.socket_path)
  request({ action: 'execute', code: code }, socket_path: socket_path)
end

.listening?(socket_path = self.socket_path) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
57
58
# File 'lib/console_ipc/connection.rb', line 53

def self.listening?(socket_path = self.socket_path)
  UNIXSocket.open(socket_path).close
  true
rescue Errno::ENOENT, Errno::ECONNREFUSED
  false
end

.monotonic_timeObject



49
50
51
# File 'lib/console_ipc/connection.rb', line 49

def self.monotonic_time
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

.reload(socket_path: self.socket_path) ⇒ Object



31
32
33
# File 'lib/console_ipc/connection.rb', line 31

def self.reload(socket_path: self.socket_path)
  request({ action: 'reload' }, socket_path: socket_path)
end

.request(payload, socket_path: self.socket_path) ⇒ Object



60
61
62
63
64
65
66
67
# File 'lib/console_ipc/connection.rb', line 60

def self.request(payload, socket_path: self.socket_path)
  UNIXSocket.open(socket_path) do |socket|
    socket.puts(JSON.generate(payload))
    JSON.parse(socket.read)
  end
rescue Errno::ENOENT, Errno::ECONNREFUSED => e
  raise ConnectionError, "No background console is listening on #{socket_path} (#{e.message})"
end

.root_pathObject



19
20
21
22
23
24
25
# File 'lib/console_ipc/connection.rb', line 19

def self.root_path
  bundle_gemfile = ENV.fetch('BUNDLE_GEMFILE', nil)

  return File.dirname(File.expand_path(bundle_gemfile)) if bundle_gemfile

  Dir.pwd
end

.socket_pathObject



13
14
15
16
17
# File 'lib/console_ipc/connection.rb', line 13

def self.socket_path
  ENV.fetch('CONSOLE_IPC_SOCKET') do
    File.expand_path(DEFAULT_SOCKET_PATH, root_path)
  end
end

.stop(socket_path: self.socket_path) ⇒ Object



35
36
37
# File 'lib/console_ipc/connection.rb', line 35

def self.stop(socket_path: self.socket_path)
  request({ action: 'stop' }, socket_path: socket_path)
end

.wait_until_stopped(socket_path: self.socket_path, timeout: STOP_WAIT_TIMEOUT_SECONDS) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/console_ipc/connection.rb', line 39

def self.wait_until_stopped(socket_path: self.socket_path, timeout: STOP_WAIT_TIMEOUT_SECONDS)
  deadline = monotonic_time + timeout

  while listening?(socket_path)
    raise ConnectionError, "Timed out waiting for background console to stop on #{socket_path}" if monotonic_time >= deadline

    sleep 0.05
  end
end