Class: Specter::Server

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cli) ⇒ Server

Returns a new instance of Server.



21
22
23
24
25
26
27
28
# File 'lib/specter/server.rb', line 21

def initialize(cli)
  @cli     = cli
  @options = cli.options

  @logger = Logger.new(STDOUT)
  @socket = TCPServer.new(options[:host], options[:port])
  @stack  = Middleware.new(self)
end

Instance Attribute Details

#cliObject (readonly)

Returns the value of attribute cli.



11
12
13
# File 'lib/specter/server.rb', line 11

def cli
  @cli
end

#loggerObject (readonly)

Returns the value of attribute logger.



15
16
17
# File 'lib/specter/server.rb', line 15

def logger
  @logger
end

#optionsObject (readonly)

Returns the value of attribute options.



13
14
15
# File 'lib/specter/server.rb', line 13

def options
  @options
end

#socketObject (readonly)

Returns the value of attribute socket.



17
18
19
# File 'lib/specter/server.rb', line 17

def socket
  @socket
end

#stackObject (readonly)

Returns the value of attribute stack.



19
20
21
# File 'lib/specter/server.rb', line 19

def stack
  @stack
end

Instance Method Details

#handle_requestsObject



35
36
37
38
39
40
# File 'lib/specter/server.rb', line 35

def handle_requests
  loop do
    client = socket.accept
    process_request(client)
  end
end

#log_error(client, e) ⇒ Object



64
65
66
67
68
69
# File 'lib/specter/server.rb', line 64

def log_error(client, e)
  logger.error "%s - %s: %s\n%s" % [
    client.remote_address.ip_address, e.class, e.message,
    e.backtrace.join("\n")
  ]
end

#log_request(env) ⇒ Object



71
72
73
74
75
# File 'lib/specter/server.rb', line 71

def log_request(env)
  logger.info "%s - %s - %s" % [
    env.client.remote_address.ip_address, env.request.command, env.request.args.inspect
  ]
end

#log_timeout(client) ⇒ Object



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

def log_timeout(client)
  logger.warn "%s - timeout" % [
    client.remote_address.ip_address
  ]
end

#process_request(client) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/specter/server.rb', line 42

def process_request(client)
  Timeout.timeout(5) do
    req = Request.parse(client.gets)
    env = Env.new(client, req)
    log_request(env)
    @stack.call(env)
    client.write env.to_str
  end
rescue Timeout::Error
  log_timeout(client)
rescue Object => e
  log_error(client, e)
ensure
  client.close rescue nil
end

#runObject



30
31
32
33
# File 'lib/specter/server.rb', line 30

def run
  BasicSocket.do_not_reverse_lookup = true
  return @thread = Thread.new { handle_requests }
end