Class: DynamoDB::HttpHandler
- Inherits:
-
Object
- Object
- DynamoDB::HttpHandler
- Defined in:
- lib/dynamodb/http_handler.rb
Overview
Process HTTP requests
Kudos to AWS’s NetHttpHandler class for the inspiration here. Re-using a single instance of this class is recommended, since it relies upon persistent HTTP connections managed by a pool.
Constant Summary collapse
- DEFAULT_TIMEOUT =
seconds
5
- NETWORK_ERRORS =
[ SocketError, EOFError, IOError, Errno::ECONNABORTED, Errno::ECONNRESET, Errno::EPIPE, Errno::EINVAL, Timeout::Error, Errno::ETIMEDOUT ]
Instance Attribute Summary collapse
-
#timeout ⇒ Object
writeonly
Sets the attribute timeout.
Instance Method Summary collapse
- #build_http_request(request) ⇒ Object
-
#handle(request) ⇒ Object
Perform an HTTP request.
-
#initialize(options = {}) ⇒ HttpHandler
constructor
A new instance of HttpHandler.
Constructor Details
#initialize(options = {}) ⇒ HttpHandler
Returns a new instance of HttpHandler.
26 27 28 29 |
# File 'lib/dynamodb/http_handler.rb', line 26 def initialize( = {}) @pool = Net::HTTP::ConnectionPool.new @timeout = [:timeout] || DEFAULT_TIMEOUT end |
Instance Attribute Details
#timeout=(value) ⇒ Object (writeonly)
Sets the attribute timeout
24 25 26 |
# File 'lib/dynamodb/http_handler.rb', line 24 def timeout=(value) @timeout = value end |
Instance Method Details
#build_http_request(request) ⇒ Object
63 64 65 66 67 68 69 70 71 |
# File 'lib/dynamodb/http_handler.rb', line 63 def build_http_request(request) Net::HTTP::Post.new(request.uri.to_s).tap do |http_request| http_request.body = request.body request.headers.each do |key, value| http_request[key] = value end end end |
#handle(request) ⇒ Object
Perform an HTTP request
The argument should be a ‘DynamoDB::Request` object, and the return value is either a `DynamoDB::SuccessResponse` or a `DynamoDB::FailureResponse`.
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 |
# File 'lib/dynamodb/http_handler.rb', line 36 def handle(request) connection = @pool.connection_for(request.uri.host, { port: request.uri.port, ssl: request.uri.scheme == "https", ssl_verify_peer: true }) connection.read_timeout = @timeout begin response = nil connection.request(build_http_request(request)) do |http_response| if http_response.code.to_i < 300 response = SuccessResponse.new(http_response) else response = FailureResponse.new(http_response) end end response rescue *NETWORK_ERRORS => e FailureResponse.new.tap do |response| response.body = nil response.code = nil response.error = e end end end |