summaryrefslogtreecommitdiff
path: root/lib/nickserver/reel_server.rb
blob: f7cc3b0a1e48cd82c6540fae087ff6c43b7e9c9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
silence_warnings do
  require 'reel'
end
require 'logger'
require 'nickserver/config'
require 'nickserver/adapters/celluloid_http'
require 'nickserver/dispatcher'
require 'nickserver/logging_responder'

module Nickserver
  class ReelServer < Reel::Server::HTTP
    DEFAULT_ADAPTER_CLASS = Nickserver::Adapters::CelluloidHttp

    def self.start(options = {})
      new(options[:host], options[:port])
    end

    def initialize(host = '127.0.0.1', port = 3000)
      Celluloid.logger = logger
      super(host, port, &method(:on_connection))
    end

    def handle_connection(*args)
      silence_warnings do
        super
      end
    end

    def on_connection(connection)
      connection.each_request do |request|
        handle_request(request)
      end
    end

    protected

    def handle_request(request)
      logging_request(request) do
        with_http_adapter do |adapter|
          handler = handler_for(request, adapter)
          handler.respond_to params(request), request.headers
        end
      end
    rescue StandardError
      request.respond 500, '{}'
    end

    def logging_request(request)
      logger.info "#{request.method} #{request.uri}"
      logger.debug "  #{params(request)}"
      yield
    rescue StandardError => e
      logger.error e
      logger.error e.backtrace.join "\n  "
      raise
    end

    def with_http_adapter
      adapter = DEFAULT_ADAPTER_CLASS.new
      yield adapter
    ensure
      adapter.terminate if adapter.respond_to? :terminate
    end

    def handler_for(request, adapter)
      # with reel the request is the responder
      responder = LoggingResponder.new(request, logger)
      Dispatcher.new(responder, adapter)
    end

    def params(request)
      if request.query_string
        CGI.parse request.query_string
      else
        CGI.parse request.body.to_s
      end
    end

    def logger
      @logger ||= ::Logger.new Config.log_file
    end
  end
end