Class: Falcon::Proxy

Inherits:
Async::HTTP::Middleware
  • Object
show all
Defined in:
lib/falcon/proxy.rb

Constant Summary collapse

X_FORWARDED_FOR =
'x-forwarded-for'.freeze
VIA =
'via'.freeze
CONNECTION =
Async::HTTP::Protocol::HTTP11::CONNECTION
HOP_HEADERS =
[
  'connection',
  'keep-alive',
  'public',
  'proxy-authenticate',
  'transfer-encoding',
  'upgrade',
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, hosts) ⇒ Proxy

Returns a new instance of Proxy.



47
48
49
50
51
52
53
54
55
56
# File 'lib/falcon/proxy.rb', line 47

def initialize(app, hosts)
  super(app)
  
  @server_context = nil
  
  @hosts = hosts
  @clients = {}
  
  @count = 0
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



58
59
60
# File 'lib/falcon/proxy.rb', line 58

def count
  @count
end

Instance Method Details

#call(request) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/falcon/proxy.rb', line 85

def call(request)
  if endpoint = lookup(request)
    @count += 1
    
    if address = request.remote_address
      request.headers.add(X_FORWARDED_FOR, address.ip_address)
    end
    
    request.headers.add(VIA, "#{request.version} #{self.class}")
    
    client = connect(endpoint)
    
    prepare_headers(request.headers)
    client.call(request)
  else
    super
  end
rescue
  Async.logger.error(self) {$!}
  return Async::HTTP::Response[502, {'content-type' => 'text/plain'}, ["#{$!.inspect}: #{$!.backtrace.join("\n")}"]]
end

#closeObject



60
61
62
63
64
# File 'lib/falcon/proxy.rb', line 60

def close
  @clients.each_value(&:close)
  
  super
end

#connect(endpoint) ⇒ Object



66
67
68
# File 'lib/falcon/proxy.rb', line 66

def connect(endpoint)
  @clients[endpoint] ||= Async::HTTP::Client.new(endpoint)
end

#lookup(request) ⇒ Object



70
71
72
73
74
75
# File 'lib/falcon/proxy.rb', line 70

def lookup(request)
  # Trailing dot and port is ignored/normalized.
  if authority = request.authority.sub(/(\.)?(:\d+)?$/, '')
    return @hosts[authority]
  end
end

#prepare_headers(headers) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/falcon/proxy.rb', line 77

def prepare_headers(headers)
  if connection = headers[CONNECTION]
    headers.slice!(connection)
  end
  
  headers.slice!(HOP_HEADERS)
end