Class: ThreadServer

Inherits:
Object
  • Object
show all
Includes:
ServerBase
Defined in:
lib/macaw_framework/core/thread_server.rb

Overview

Class responsible for providing a default webserver with Ruby Threads. This Server is subject to the MRI Global Interpreter Lock, thus it will use only a single physical Thread.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from CacheAspect

#call_endpoint

Methods included from LoggingAspect

#call_endpoint

Methods included from PrometheusAspect

#call_endpoint

Constructor Details

#initialize(macaw, endpoints_to_cache = nil, cache = nil, prometheus = nil, prometheus_mw = nil) ⇒ Server

Create a new instance of ThreadServer.

Parameters:

  • macaw (Macaw)
  • logger (Logger)
  • port (Integer)
  • bind (String)
  • num_threads (Integer)
  • cache (MemoryInvalidationMiddleware) (defaults to: nil)
  • prometheus (Prometheus::Client:Registry) (defaults to: nil)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/macaw_framework/core/thread_server.rb', line 28

def initialize(macaw, endpoints_to_cache = nil, cache = nil, prometheus = nil, prometheus_mw = nil)
  @port = macaw.port
  @bind = macaw.bind
  @macaw = macaw
  @macaw_log = macaw.macaw_log
  @num_threads = macaw.threads
  @work_queue = Queue.new
  set_features
  @rate_limit ||= nil
  @cache = {
    cache: cache,
    endpoints_to_cache: endpoints_to_cache || [],
    cached_methods: macaw.cached_methods
  }
  @prometheus = prometheus
  @prometheus_middleware = prometheus_mw
  @workers = []
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



14
15
16
# File 'lib/macaw_framework/core/thread_server.rb', line 14

def context
  @context
end

Instance Method Details

#runObject

Start running the webserver.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/macaw_framework/core/thread_server.rb', line 51

def run
  @server = TCPServer.new(@bind, @port)
  @server = OpenSSL::SSL::SSLServer.new(@server, @context) if @context
  @workers_mutex = Mutex.new
  @num_threads.times do
    spawn_worker
  end

  Thread.new do
    loop do
      sleep 10
      maintain_worker_pool
    end
  end

  loop do
    @work_queue << @server.accept unless @is_shutting_down
  rescue OpenSSL::SSL::SSLError => e
    @macaw_log&.error("SSL error: #{e.message}")
  rescue IOError, Errno::EBADF
    break
  end
end

#shutdownObject

Method Responsible for closing the TCP server.



77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/macaw_framework/core/thread_server.rb', line 77

def shutdown
  @is_shutting_down = true
  loop do
    break if @work_queue.empty?

    sleep 0.1
  end

  @num_threads.times { @work_queue << :shutdown }
  @workers.each(&:join)
  @server.close
end