Class: SlowServer::Server

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

Instance Method Summary collapse

Instance Method Details

#chunk_sizeObject



14
15
16
# File 'lib/slow_server/server.rb', line 14

def chunk_size
  (config.response_body.size / config.chunks.to_f).round
end

#chunksObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/slow_server/server.rb', line 19

def chunks
  #config.response_body.scan(/.{1,#{chunk_size}}/m)
  # NOTE: to be accurate, chunk_size needs to be variable, or at least increase in a giant burst at the end
  #

  offset = 0
  length = 0
  out = []
  config.chunks.times do |i|
    length = ((config.response_body.size - out.join.size) / (config.chunks - i).to_f).floor
    out << config.response_body[offset..(offset+length)]
    offset += length + 1
  end
  out
end

#configObject



6
7
8
# File 'lib/slow_server/server.rb', line 6

def config
  @config ||= ServerConfig.new
end

#get_request(socket) ⇒ Object



45
46
47
48
# File 'lib/slow_server/server.rb', line 45

def get_request(socket)
  STDERR.puts socket.gets
  STDERR.puts "Waiting for #{config.response_delay} seconds"
end

#response_headersObject



36
37
38
39
40
41
42
43
# File 'lib/slow_server/server.rb', line 36

def response_headers
  [].tap do |h|
    h << "HTTP/1.1 200 OK"
    h << "Content-Type: text/plain"
    h << "Content-Length: #{config.response_body.size}"
    h << "Connection: close"
  end
end

#send_response(socket) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/slow_server/server.rb', line 50

def send_response(socket)
  STDERR.puts "Sending response headers"
  socket.print response_headers.join("\n")
  socket.print "\r\n\r\n"
  chunks.each do |chunk|
    STDERR.puts "Sending #{chunk_size} bytes"
    socket.print chunk
    STDERR.puts "Waiting for #{config.chunk_delay} seconds"
    sleep config.chunk_delay
  end
end

#serverObject



10
11
12
# File 'lib/slow_server/server.rb', line 10

def server
  @server ||= TCPServer.open('0.0.0.0', config.port)
end

#startObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/slow_server/server.rb', line 62

def start
  loop do
    Thread.start(server.accept) do |socket|
      STDERR.puts "Accepted Connection"
      # NOTE: consider putting a delay in here too
      get_request(socket)

      sleep config.response_delay

      send_response(socket)
      STDERR.print "\n"
      socket.close
    end
  end
end