Class: Takagi::Server::Multi

Inherits:
Object
  • Object
show all
Defined in:
lib/takagi/server/multi.rb

Overview

Helper class to run multiple servers concurrently

Instance Method Summary collapse

Constructor Details

#initialize(servers) ⇒ Multi

Returns a new instance of Multi.



7
8
9
10
# File 'lib/takagi/server/multi.rb', line 7

def initialize(servers)
  @servers = servers
  @threads = []
end

Instance Method Details

#run!Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/takagi/server/multi.rb', line 12

def run!
  # Set flag instead of calling shutdown! directly from trap context
  # This avoids "can't be called from trap context" errors with logger
  trap('INT') { @shutdown_requested = true }

  @threads = @servers.map { |srv| Thread.new { srv.run! } }

  # Monitor threads and check for shutdown signal
  until @threads.all? { |t| !t.alive? } || @shutdown_requested
    sleep 0.1
  end

  # Call shutdown if it was requested by signal
  shutdown! if @shutdown_requested

  @threads.each(&:join)
end

#shutdown!Object



30
31
32
33
34
35
36
37
38
# File 'lib/takagi/server/multi.rb', line 30

def shutdown!
  @servers.each(&:shutdown!)
  @threads.each(&:join)

  # Join the server thread if it was spawned via spawn!
  if defined?(@server_thread) && @server_thread&.alive?
    @server_thread.join(5) # Wait up to 5 seconds
  end
end