Repository URL to install this package:
|
Version:
2.2.0 ▾
|
# frozen_string_literal: true
require 'base64'
require 'json'
require 'logger'
module Sinatra
# Helpers for production - using AWS Cognito
module LambdaHandler
module_function
# From https://github.com/aws-samples/serverless-sinatra-sample/blob/master/lambda.rb
# Modified by systems to add KeepAlive
# Since this is not our code...
# rubocop:disable all
def handler(event:, context:, multi_value_headers: false)
logger = Logger.new $stdout
unless event['httpMethod']
# Catch false events
# interpret as KeepAlive (keep warm)
response = {
'statusCode' => 200,
'body' => 'KeepAlive executed OK'
}
response
else
# Check if the body is base64 encoded. If it is, try to decode it
body = if event['isBase64Encoded']
Base64.decode64 event['body']
else
event['body']
end || ''
# Rack expects the querystring in plain text, not a hash
headers = if multi_value_headers
event.fetch('multiValueHeaders', {}).transform_values { |v| v.length == 1 ? v[0] : v }
else
event.fetch('headers', {})
end
# Environment required by Rack (http://www.rubydoc.info/github/rack/rack/file/SPEC)
env = {
'REQUEST_METHOD' => event.fetch('httpMethod'),
'SCRIPT_NAME' => '',
'PATH_INFO' => event.fetch('path', ''),
'QUERY_STRING' => Rack::Utils.unescape(Rack::Utils.build_query(
event[multi_value_headers ? 'multiValueQueryStringParameters' : 'queryStringParameters'] || {}
)),
'SERVER_NAME' => headers.fetch('Host', 'localhost'),
'SERVER_PORT' => headers.fetch('X-Forwarded-Port', 443).to_s,
'rack.version' => Rack::VERSION,
'rack.url_scheme' => headers.fetch('CloudFront-Forwarded-Proto') { headers.fetch('X-Forwarded-Proto', 'https') },
'rack.input' => StringIO.new(body),
'rack.errors' => $stderr,
}
# Pass request headers to Rack if they are available
headers.each_pair do |key, value|
# 'CloudFront-Forwarded-Proto' => 'CLOUDFRONT_FORWARDED_PROTO'
# Content-Type and Content-Length are handled specially per the Rack SPEC linked above.
name = key.upcase.gsub '-', '_'
header = case name
when 'CONTENT_TYPE', 'CONTENT_LENGTH'
name
else
"HTTP_#{name}"
end
env[header] = value.to_s
end
logger.info(env.slice *%w(REQUEST_METHOD PATH_INFO QUERY_STRING HTTP_HOST HTTP_X_FORWARDED_FOR))
begin
# Response from Rack must have status, headers and body
status, headers, body = $app.call env
# body is an array. We combine all the items to a single string
body_content = ""
body.each do |item|
body_content += item.to_s
end
# We return the structure required by AWS API Gateway since we integrate with it
# https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
response = {
'statusCode' => status,
'headers' => headers,
'body' => body_content
}
if multi_value_headers
response['multiValueHeaders'] = headers.transform_values { |v| [v] }
else
response['headers'] = headers
end
if event['requestContext'].has_key?('elb')
# Required if we use Application Load Balancer instead of API Gateway
if body_content.encoding == Encoding::UTF_8
response['isBase64Encoded'] = false
else
response['isBase64Encoded'] = true
response['body'] = Base64.strict_encode64 body_content
end
end
logger.info"Response Status #{status}"
rescue Exception => exception
# If there is _any_ exception, we return a 500 error with an error message
response = {
'statusCode' => 500,
'body' => exception.message
}
logger.fatal response
logger.fatal exception.backtrace.join("\n\t") if exception.backtrace
end
# By default, the response serializer will call #to_json for us
response
end
end
# rubocop:enable all
end
end