Class: Adelnor::RactorServer

Inherits:
BaseServer show all
Defined in:
lib/adelnor/ractor_server.rb

Instance Method Summary collapse

Methods inherited from BaseServer

#handle, #rack_data, #read_request_message, run, #welcome_message

Constructor Details

#initialize(rack_app, port, options = {}) ⇒ RactorServer

Returns a new instance of RactorServer.



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
# File 'lib/adelnor/ractor_server.rb', line 8

def initialize(rack_app, port, options = {})
  @ractors = options[:ractors]

  @rack_app = rack_app
  @port     = port
  @options  = options

  @queue = Ractor.new do
    loop do
      Ractor.yield(Ractor.receive, move: true)
    end
  end

  @listener = Ractor.new(@queue, @port) do |queue, port|
    socket = Socket.new(:INET, :STREAM)
    addr = Socket.sockaddr_in(port, '0.0.0.0')

    socket.bind(addr)
    socket.listen(2)

    loop do
      client, = socket.accept

      queue.send(client, move: true)
    end
  end

  puts welcome_message
end

Instance Method Details

#runObject



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
84
85
86
87
88
# File 'lib/adelnor/ractor_server.rb', line 38

def run
  ractors = @ractors.times.map do
    Ractor.new(@queue, @rack_app, @port) do |queue, rack_app, port|
      rid = Ractor.current.object_id
      puts "[#{rid}] Ractor started"

      loop do
        client = queue.take
        message = ''

        if (line = client.gets)
          message += line
        end

        puts "\n[#{Time.now}] #{message}"

        while (line = client.gets)
          break if line == "\r\n"

          message += line
        end

        rack_data = lambda do |request|
          {
            'REQUEST_METHOD' => request.request_method,
            'PATH_INFO' => request.path_info,
            'QUERY_STRING' => request.query_string,
            'SERVER_PORT' => port,
            'SERVER_NAME' => request.headers['Host'],
            'CONTENT_LENGTH' => request.content_length,
            'HTTP_COOKIE' => request.headers['Cookie'],
            'rack.input' => StringIO.new(request.body)
          }
        end

        Request.build(message)
               .tap  { |request|  request.parse_body!(client) }
               .then { |request|  rack_data.call(request).merge(request.headers) }
               .then { |data|     rack_app.call(data) }
               .then { |result|   Response.build(*result) }
               .then { |response| client.puts(response) }

        client.close
      end
    end
  end

  loop do
    Ractor.select(@listener, *ractors)
  end
end