Class: Cougar::Server

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, host: "localhost", port: 9292, workers: ENV.fetch("RUBY_MAX_CPU", 8).to_i) ⇒ Server

Returns a new instance of Server.



10
11
12
13
14
15
16
17
# File 'lib/cougar/server.rb', line 10

def initialize(app, host: "localhost", port: 9292, workers: ENV.fetch("RUBY_MAX_CPU", 8).to_i)
  @app = app
  @host = host
  @port = port
  @workers = workers
  @server = nil
  @workers_list = []
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



8
9
10
# File 'lib/cougar/server.rb', line 8

def app
  @app
end

#hostObject (readonly)

Returns the value of attribute host.



8
9
10
# File 'lib/cougar/server.rb', line 8

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



8
9
10
# File 'lib/cougar/server.rb', line 8

def port
  @port
end

#workersObject (readonly)

Returns the value of attribute workers.



8
9
10
# File 'lib/cougar/server.rb', line 8

def workers
  @workers
end

Instance Method Details

#inspectObject



58
59
60
61
# File 'lib/cougar/server.rb', line 58

def inspect
  worker_statuses = status
  "#<#{self.class.name}:0x#{object_id.to_s(16)} @host=#{@host.inspect} @port=#{@port} @workers=#{@workers} workers=#{worker_statuses.inspect}>"
end

#runObject



36
37
38
39
40
41
# File 'lib/cougar/server.rb', line 36

def run
  start

  # Wait for workers to finish
  @workers_list.each(&:join)
end

#startObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/cougar/server.rb', line 19

def start
  silence_ractor_warning!

  @server = TCPServer.new(@host, @port)
  @port = @server.addr[1]  # Get the actual port if it was 0
  puts "Cougar listening on #{@host}:#{@port} with #{@workers} workers"

  # Freeze the app so it can be shared across Ractors
  @app.freeze

  # Create worker Ractors
  @workers.times do |i|
    worker = RactorWorker.new(i, @server, @app)
    @workers_list << worker
  end
end

#statusObject



49
50
51
52
53
54
55
56
# File 'lib/cougar/server.rb', line 49

def status
  response_port = Ractor::Port.new
  workers = @workers_list
  workers.each { |worker| worker.send_status_request(response_port) }
  statuses = workers.size.times.map { response_port.receive }
  response_port.close
  statuses
end

#stopObject



43
44
45
46
47
# File 'lib/cougar/server.rb', line 43

def stop
  @server.close

  @workers_list.each(&:stop)
end