Skip to content

Commit

Permalink
Merge pull request #242 from tongueroo/adjust-for-elb
Browse files Browse the repository at this point in the history
adjust resp when request coming from elb
  • Loading branch information
tongueroo committed May 2, 2019
2 parents 0c7e628 + 2220db2 commit af4bb74
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
27 changes: 26 additions & 1 deletion lib/jets/controller/rack/adapter.rb
Expand Up @@ -33,12 +33,37 @@ def convert_to_api_gateway(status, headers, body)
base64 = headers["x-jets-base64"] == 'yes'
body = body.respond_to?(:read) ? body.read : body
body = Base64.encode64(body) if base64
{

resp = {
"statusCode" => status,
"headers" => headers,
"body" => body,
"isBase64Encoded" => base64,
}
adjust_for_elb(resp)
resp
end

# Note: ELB is not officially support. This is just in case users wish to manually
# connect ELBs to the functions created by Jets.
def adjust_for_elb(resp)
return resp unless from_elb?

# ELB requires statusCode to be an Integer whereas API Gateway requires statusCode to be a String
status = resp["statusCode"] = resp["statusCode"].to_i

# ELB also requires statusDescription attribute
status_desc = Rack::Utils::HTTP_STATUS_CODES[status]
status_desc = status_desc.nil? ? status.to_s : "#{status} #{status_desc}"
resp["statusDescription"] = status_desc

resp
end

def from_elb?
# NOTE: @event["requestContext"]["elb"] is set when the request is coming from an elb
# Can set JETS_ELB=1 for local testing
@event["requestContext"] && @event["requestContext"]["elb"] || ENV['JETS_ELB']
end

# Called from Jets::Controller::Base.process. Example:
Expand Down
6 changes: 5 additions & 1 deletion lib/jets/controller/rendering/rack_renderer.rb
Expand Up @@ -165,7 +165,11 @@ def normalize_status_code(code)
else
code
end
(status_code || 200).to_s # API Gateway requires a string but rack is okay with either

# API Gateway requires status to be String but local rack is okay with either
# Note, ELB though requires status to be an Integer. We'll later in rack/adapter.rb
# adjust status to an Integer if request is coming from an ELB.
(status_code || 200).to_s
end

def set_content_type!(status, headers)
Expand Down
6 changes: 4 additions & 2 deletions lib/jets/processors/main_processor.rb
Expand Up @@ -35,8 +35,10 @@ def run
Jets.increase_call_count

if result.is_a?(Hash) && result["headers"]
result["headers"]["x-jets-call-count"] = Jets.call_count
result["headers"]["x-jets-prewarm-count"] = Jets.prewarm_count
# API Gateway is okay with the header values as Integers but
# ELBs are more strict about this and require the header values to be Strings
result["headers"]["x-jets-call-count"] = Jets.call_count.to_s
result["headers"]["x-jets-prewarm-count"] = Jets.prewarm_count.to_s
end

result
Expand Down

0 comments on commit af4bb74

Please sign in to comment.