Class: Yup::State::RequestForwarder

Inherits:
Object
  • Object
show all
Defined in:
lib/yup/state.rb

Instance Method Summary collapse

Constructor Details

#initialize(state, forward_to, timeout) ⇒ RequestForwarder

Returns a new instance of RequestForwarder.



14
15
16
17
18
19
20
21
22
23
# File 'lib/yup/state.rb', line 14

def initialize(state, forward_to, timeout)
  @state      = state
  @forward_to = forward_to
  @timeout    = timeout
  @logger     = Yup.logger.clone
  @logger.progname = "Yup::State::RequestForwarder"

  @yajl = Yajl::Parser.new(:symbolize_keys => true)
  @yajl.on_parse_complete = self.method(:make_request)
end

Instance Method Details

#make_request(req) ⇒ Object



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
# File 'lib/yup/state.rb', line 36

def make_request(req)
  begin
    @http_method, @request_url, headers, body = req
    headers = Hash[*headers.to_a.flatten.map(&:to_s)]
    headers["Host"]       = @forward_to
    headers["Connection"] = "Close"

    req = "#{@http_method.upcase} #{@request_url} HTTP/1.1\r\n"
    headers.each do |k, v|
      req << "#{k}: #{v}\r\n"
    end
    req << "\r\n"
    req << body if !body.empty?
    raw_response = send_data(req.to_s, @forward_to)

    response_body = ""
    http = Http::Parser.new()
    http.on_body = proc do |chunk|
      response_body << chunk
    end
    http << raw_response

    if http.status_code && http.status_code / 100 == 2
      log_response(raw_response, response_body, http)
      @logger.info "Success"
    else
      log_response(raw_response, response_body, http)
      if Yup.retry_unless_2xx
        @logger.info "Fail: got status code #{http.status_code}; will retry after #{Yup.resend_delay} seconds"
        @state.pushback(Yajl::Encoder.encode([@http_method.downcase, @request_url, headers, body]))

        sleep Yup.resend_delay
      else
        @logger.info "Fail; will not retry"
      end
    end

  rescue Exception, Timeout::Error => e
    log_response(raw_response, response_body, http)
    @logger.info "Error: #{e.class}: #{e.message}; will retry after #{Yup.resend_delay} seconds"

    @state.pushback(Yajl::Encoder.encode([@http_method.downcase, @request_url, headers, body]))

    sleep Yup.resend_delay
  end
end

#run_loopObject



25
26
27
28
29
30
31
32
33
34
# File 'lib/yup/state.rb', line 25

def run_loop
  loop do
    data = @state.bpop
    begin
      @yajl << data
    rescue Yajl::ParseError
      @logger.error { "Error while parsing \"#{data}\"" }
    end
  end
end