Class: Sbmt::Pact::Provider::HttpServer

Inherits:
Object
  • Object
show all
Defined in:
lib/sbmt/pact/provider/http_server.rb

Overview

inspired by Gruf::Cli::Executor

Constant Summary collapse

SERVER_STOP_TIMEOUT_SEC =
15

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ HttpServer

Returns a new instance of HttpServer.



10
11
12
13
14
15
16
17
# File 'lib/sbmt/pact/provider/http_server.rb', line 10

def initialize(options = {})
  @options = options

  @server_pid = nil

  @host = @options[:host] || "localhost"
  @logger = @options[:logger] || ::Logger.new($stdout)
end

Instance Method Details

#runObject

Run the server



53
54
55
56
57
58
59
60
61
62
# File 'lib/sbmt/pact/provider/http_server.rb', line 53

def run
  start

  yield
rescue => e
  @logger.fatal("FATAL ERROR: #{e.message} #{e.backtrace.join("\n")}")
  raise
ensure
  stop
end

#startObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/sbmt/pact/provider/http_server.rb', line 19

def start
  raise "server already running, stop server before starting new one" if @thread

  @logger.info("[webrick] starting server with options: #{@options}")

  @thread = Thread.new do
    @logger.debug "[webrick] starting http server"

    ::Rack::Handler::WEBrick.run(Rails.application,
      Host: @options[:host],
      Port: @options[:port],
      Logger: @logger,
      StartCallback: -> { @started = true }) do |server|
      @server = server
    end
  end
  sleep 0.001 until @started

  @logger.info("[webrick] server started")
end

#stopObject



40
41
42
43
44
45
46
47
48
# File 'lib/sbmt/pact/provider/http_server.rb', line 40

def stop
  @logger.info("[webrick] stopping server")

  @server&.shutdown
  @thread&.join(SERVER_STOP_TIMEOUT_SEC)
  @thread&.kill

  @logger.info("[webrick] server stopped")
end