Class: Spyder::Server

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bind, port, router: Router.new, max_threads: 4, tcp_backlog: 10) ⇒ Server

Returns a new instance of Server.



7
8
9
10
11
12
13
14
15
# File 'lib/spyder/server.rb', line 7

def initialize(bind, port, router: Router.new, max_threads: 4, tcp_backlog: 10)
  @server = TCPServer.new(bind, port)
  @tcp_backlog = tcp_backlog
  @max_threads = max_threads
  @middleware = []
  @threads = []
  @tp_sync = Mutex.new
  @router = router
end

Instance Attribute Details

#routerObject

Returns the value of attribute router.



5
6
7
# File 'lib/spyder/server.rb', line 5

def router
  @router
end

Instance Method Details

#add_middleware(callable, args) ⇒ Object



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

def add_middleware(callable, args)
  @middleware << [callable, args]
end

#dispatch_response(socket, response) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/spyder/server.rb', line 98

def dispatch_response(socket, response)
  content_length = response.headers.dict['content-length']
  if !content_length && response.body && response.body.is_a?(String)
    content_length = response.body.length
  end

  begin
    socket.write("HTTP/1.1 #{response.code} #{response.reason_sentence.b}\r\n")
    response.headers.ordered.each do |name, value|
      socket.write("#{name.b}: #{value.b}\r\n")
    end
    socket.write("connection: close\r\n") # FIXME:
    socket.write("content-length: #{content_length}\r\n") if content_length
    socket.write("\r\n")

    if response.body
      Array(response.body).each do |part|
        content = part.respond_to?(:call) ? part.call : part
        socket.write(content.b)
      end
    end
  rescue Errno::EPIPE
    # socket closed. So what?
    socket.close rescue nil
  end
end

#process_new_client(socket) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/spyder/server.rb', line 77

def process_new_client(socket)
  verb, path, protocol = read_line(socket).split(' ')
  request = Request.new
  request.path = path
  request.verb = verb
  request.io = socket

  loop do
    line = read_line(socket)
    break if line == ''
    sep = line.index(':')
    name = line[0...sep].downcase
    value = line[(sep + 2)..]
    request.add_header(name, value)
  end

  response = process_request(request)

  dispatch_response(socket, response)
end

#process_request(request) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/spyder/server.rb', line 65

def process_request(request)
  mids = @middleware + [[RouterApp, @router]]
  app = nil
  loop do
    klass, args = mids.pop
    break unless klass
    app = klass.new(args, app)
  end

  app.call({}, request)
end

#read_line(socket) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/spyder/server.rb', line 125

def read_line(socket)
  line_limit = 1024 * 16
  buffer = String.new(capacity: 128)
  almost = false
  loop do
    line_limit -= 1
    return false unless line_limit > 0

    c = socket.readchar
    if !almost && c == "\r"
      almost = true
    elsif almost
      return false unless c == "\n"
      return buffer
    else
      buffer += c
    end
  end
end

#startObject



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
# File 'lib/spyder/server.rb', line 21

def start
  busy_threads = 0
  @server.listen(@tcp_backlog)

  loop do
    time_start = Process.clock_gettime(:CLOCK_MONOTONIC, :float_second)
    loop do
      current_busy = @tp_sync.synchronize { busy_threads }
      break if current_busy < @max_threads
      sleep(0)
      current_time = Process.clock_gettime(:CLOCK_MONOTONIC, :float_second)
      if (current_time - time_start) > 1.0
        # puts "Waiting a long time: #{(current_time - time_start)}"
        sleep 0.2
      end
    end

    client = @server.accept
    @tp_sync.synchronize { busy_threads += 1 }

    Thread.new do
      begin
        error = nil
        begin
          process_new_client(client)
        rescue Exception => e
          error = e
        end

        if error
          puts error.full_message

          response = Response.make_generic :internal_server_error
          dispatch_response(client, response)
        end

        client.close rescue nil
      ensure
        @tp_sync.synchronize { busy_threads -= 1 }
      end
    end
  end
end