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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Services::ES

#client, #cluster_health, #conn, #ssl_store

Instance Attribute Details

#streamingObject (readonly)

Returns the value of attribute streaming.



12
13
14
# File 'lib/proxes/forwarder.rb', line 12

def streaming
  @streaming
end

Class Method Details

.normalize_headers(headers) ⇒ Object



59
60
61
62
63
64
# File 'lib/proxes/forwarder.rb', line 59

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

#backendObject



14
15
16
# File 'lib/proxes/forwarder.rb', line 14

def backend
  @backend ||= URI(ENV['ELASTICSEARCH_URL'])
end

#backend=(var) ⇒ Object



18
19
20
# File 'lib/proxes/forwarder.rb', line 18

def backend=(var)
  @backend = URI(var)
end

#body_from(request) ⇒ Object



53
54
55
56
# File 'lib/proxes/forwarder.rb', line 53

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



22
23
24
25
26
27
# File 'lib/proxes/forwarder.rb', line 22

def call(env)
  forward(env)
rescue SocketError
  headers = { 'Content-Type' => 'application/json' }
  [500, headers, ['{"error":"Could not connect to Elasticsearch"}']]
end

#forward(env) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/proxes/forwarder.rb', line 29

def forward(env)
  source = Rack::Request.new(env)
  conn.basic_auth backend.user, backend.password
  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



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/proxes/forwarder.rb', line 40

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