Class: ProxES::Forwarder

Inherits:
Object
  • Object
show all
Includes:
Services::ES, Singleton
Defined in:
lib/proxes/forwarder.rb

Overview

A lot of code in this comes from Rack::Proxy

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Services::ES

#client, #conn, #ssl_store

Class Method Details

.normalize_headers(headers) ⇒ Object



41
42
43
44
45
46
# File 'lib/proxes/forwarder.rb', line 41

def normalize_headers(headers)
  mapped = headers.map do |k, v|
    [k, v.is_a?(Array) ? v.join("\n") : v]
  end
  Rack::Utils::HeaderHash.new Hash[mapped]
end

Instance Method Details

#body_from(request) ⇒ Object



35
36
37
38
# File 'lib/proxes/forwarder.rb', line 35

def body_from(request)
  return nil if request.body.nil? || (Kernel.const_defined?('::Puma::NullIO') && request.body.is_a?(Puma::NullIO))
  request.body.read.tap { |_r| request.body.rewind }
end

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/proxes/forwarder.rb', line 12

def call(env)
  source = Rack::Request.new(env)
  response = conn.send(source.request_method.downcase) do |req|
    source_body = body_from(source)
    req.body = source_body if source_body
    req.url source.fullpath == '' ? URI.parse(env['REQUEST_URI']).request_uri : source.fullpath
  end
  mangle response
end

#mangle(response) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/proxes/forwarder.rb', line 22

def mangle(response)
  headers = (response.respond_to?(:headers) && response.headers) || self.class.normalize_headers(response.to_hash)
  body    = response.body || ['']
  body    = [body] unless body.respond_to?(:each)

  # Not sure where this is coming from, but it causes timeouts on the client
  headers.delete('transfer-encoding')
  # Ensure that the content length rack middleware kicks in
  headers.delete('content-length')

  [response.status, headers, body]
end