• Stars
    star
    169
  • Rank 224,453 (Top 5 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 3 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Rake-like DSL for writing AWS Lambda handlers

λake

gem rspec coverage maintainability

ko-fi

Write your AWS Lambda function handlers using a Rake-like declarative syntax:

# ./lambda_function.rb
require 'yake'

handler :lambda_handler do |event|
  # Your code here
end

# Handler signature: `lambda_function.lambda_handler`

You can even declare Sinatra-like API Gateway routes for a main entrypoint:

# ./lambda_function.rb
require 'yake/api'

header 'content-type' => 'application/json'

get '/fizz' do
  respond 200, { ok: true }.to_json
end

handler :lambda_handler do |event|
  route event
rescue => err
  respond 500, { message: err.message }.to_json
end

# Handler signature: `lambda_function.lambda_handler`

Installation

Add this line to your application's Gemfile:

gem 'yake'

And then execute:

bundle install

Or install it yourself as:

gem install yake

Why Is It Called "yake"?

"λ" + Rake, but "λ" is hard to type and I think "y" looks like a funny little upside-down-and-backwards Lambda symbol.

Why Use It?

So why use yake for your Lambda functions?

Event Logging

By default, the handler function wraps its block in log lines formatted to match the style of Amazon's native Lambda logs sent to CloudWatch. Each invocation of the handler will log both the input event and the returned value, prefixed with the ID of the request:

START RequestId: 149c500f-028a-4b57-8977-0ef568cf8caf Version: $LATEST
INFO RequestId: 149c500f-028a-4b57-8977-0ef568cf8caf EVENT { … }
…
INFO RequestId: 149c500f-028a-4b57-8977-0ef568cf8caf RETURN { … }
END RequestId: 149c500f-028a-4b57-8977-0ef568cf8caf
REPORT RequestId: 149c500f-028a-4b57-8977-0ef568cf8caf  Duration: 43.97 ms  Billed Duration: 44 ms  Memory Size: 128 MB  Max Memory Used: 77 MB

Logging the request ID in this way makes gathering logs lines for a particular execution in CloudWatch much easier.

You can customize or disable the logger:

logging :off              # disables logging entirely
logging pretty: false     # Logs event/result in compact JSON
logging :on, MyLogger.new # Use a custom logger

Include Yake::Logger on a class to access this logger:

class Fizz
  include Yake::Logger
end

Fizz.new.logger == Yake.logger
# => true

API Routes

A common use of Lambda functions is as a proxy for API Gateway. Oftentimes users will deploy a single Lambda function to handle all requests coming from API Gateway.

Requiring the yake/api module will add the API-specific DSL into your handler.

Define API routes using Sinatra-like syntax

any '/…' do |event|
  # Handle 'ANY /…' route key events
end

delete '/…' do |event|
  # Handle 'DELETE /…' route key events
end

get '/…' do |event|
  # Handle 'GET /…' route key events
end

head '/…' do |event|
  # Handle 'HEAD /…' route key events
end

options '/…' do |event|
  # Handle 'OPTIONS /…' route key events
end

patch '/…' do |event|
  # Handle 'PATCH /…' route key events
end

post '/…' do |event|
  # Handle 'POST /…' route key events
end

put '/…' do |event|
  # Handle 'PUT /…' route key events
end

Helper methods are also made available to help produce a response for API Gateway:

Set a default header for ALL responses:

header 'content-type' => 'application/json; charset=utf-8'
header 'x-custom-header' => 'fizz'

Produce an API Gateway-style response object:

respond 200, { ok: true }.to_json, 'x-extra-header' => 'buzz'
# {
#   "statusCode" => 200,
#   "body" => '{"ok":true}',
#   "headers" => { "x-extra-header" => "buzz" }
# }

Route an event to one of the declared routes:

handler :lambda_handler do |event|
  route event
rescue Yake::Errors::UndeclaredRoute => err
  respond 404, { message: err.message }.to_json
rescue => err
  respond 500, { message: err.message }.to_json
end

Zero Dependencies

Finally, yake does not depend on any other gems, using the Ruby stdlib only. This helps keep your Lambda packages slim & speedy.

Support Helpers

As of ~> 0.5, yake comes with a support module for common transformations.

Enable the helpers by requiring the support submodule:

require 'yake/support'

Object helpers:

MyObject.new.some_method
# => NoMethodError

MyObject.new.try(:some_method)
# => nil

10.try(:some_method) { |x| x ** 2 }
# => 100

Hash helpers:

{ a: { b: 'c', d: 'e' }, f: 'g' }.deep_keys
# => [:a, :b, :d, :f]

left  = { a: 'b', c: { d: %w[e] } }
right = { a: 'a', c: { d: %w[d] } }
left.deep_merge(right)
# => { :a => "a", :c => { :d => ["e", "d"] } }

{ a: { b: 'c', d: 'e' }, f: 'g' }.deep_transform_keys(&:to_s)
# => { "a" => { "b" => "c", "d" => "e" }, "f" => "g" }

hash = { a: { b: 'c', d: 'e' }, f: 'g' }
hash.deep_transform_keys!(&:to_s)
# => { "a" => { "b" => "c", "d" => "e" }, "f" => "g" }

{ f: 'g', a: { d: 'e', b: 'c' } }.deep_sort
# => { a: { b: 'c', d: 'e' }, f: 'g' }

{ fizz: 'buzz' }.encode64
# => "eyJmaXp6IjoiYnV6eiJ9\n"

{ fizz: 'buzz', jazz: 'fuzz' }.except(:buzz)
# => { :fizz => 'buzz' }

{ fizz: 'buzz' }.strict_encode64
# => "eyJmaXp6IjoiYnV6eiJ9"

{ fizz: { buzz: %w[jazz fuzz] } }.stringify_names
# => { "fizz" => { "buzz" => ["jazz", "fuzz"] } }

{ 'fizz' => { 'buzz' => %w[jazz fuzz] } }.symbolize_names
# => { :fizz => { :buzz => ["jazz", "fuzz"] } }

{ fizz: 'buzz' }.to_form
# => "fizz=buzz"

{ f: 'g', a: { d: 'e', b: 'c' } }.to_json_sorted
# => '{"a":{"b":"c","d":"e"},"f":"g"}'

{ f: 'g', a: { d: 'e', b: 'c' } }.to_struct
# => #<OpenStruct f="g", a={:d=>"e", :b=>"c"}>

{ f: 'g', a: { d: 'e', b: 'c' } }.to_deep_struct
# => #<OpenStruct f="g", a=#<OpenStruct d="e", b="c">>

{ a: { b: 'c', d: 'e' }, f: 'g' }.to_dynamodb
# => { :a => { :M => { :b => { :S => "c" }, :d => { :S => "e" } } }, :f => { :S => "g" } }

{ a: { M: { b: { S: 'c' }, d: { S: 'e' } } }, f: { S: 'g' } }.to_h_from_dynamodb
# => { :a => { :b => "c", :d => "e" }, :f => "g" }

Integer helpers:

7.weeks
# => 4_233_600

7.days
# => 604_800

7.hours
# => 25_200

7.minutes
# => 420

1234567890.utc
# => 2009-02-13 23:31:30 UTC

String helpers:

host = 'https://example.com/'
path = '/path/to/resource'
host / path
# => "https://example.com/path/to/resource"

'snake_case_string'.camel_case
# => "SnakeCaseString"

"Zml6eg==\n".decode64
# => "fizz"

'fizz'.encode64
# => "Zml6eg==\n"

'fizz'.md5sum
# => "b6bfa6c318811be022d4f73070597660"

'fizz'.sha1sum
# => "c25f5985f2ab63baeb2408a2d7dbc79d8f29d02f"

'CamelCaseString'.snake_case
# => "camel_case_string"

'Zml6eg=='.strict_decode64
# => "fizz"

'fizz'.strict_encode64
# => "Zml6eg=="

'{"fizz":"buzz"}'.to_h_from_json
# => { "fizz" => "buzz" }

'fizz=buzz'.to_h_from_form
# => { "fizz" => "buzz" }

'2009-02-13T23:31:30Z'.utc
# => 2009-02-13 23:31:30 UTC

Symbol helpers

:snake_case_symbol.camel_case
# => :SnakeCaseSymbol

:CamelCaseSymbol.snake_case
# => :camel_case_symbol

UTC Time helpers

UTC.at 1234567890
# => 2009-02-13 23:31:30 UTC

UTC.now
# => 2022-02-26 13:57:07.860539 UTC

Datadog Integration

As of v1.0, yake comes with a helper for writing Lambdas that integrate with Datadog's datadog-lambda gem.

As of ~> 0.8, yake uses the v2 Datadog Lambda gem.

Creating a Lambda handler that wraps the Datadog tooling is easy:

require 'aws-sdk-someservice'
require 'yake/datadog'

# Configure Datadog to use AWS tracing
Datadog::Lambda.configure_apm { |c| c.tracing.instrument :aws }

datadog :handler do |event|
  # …
end

Deployment

After writing your Lambda handler code you can deploy it to AWS using any number of tools. I recommend the following tools:

  • Terraform — my personal favorite Infrastructure-as-Code tool
  • AWS SAM — a great alternative with less configuration than Terraform
  • Serverless — Supposedly the most popular option, though I have not used it

Development

After checking out the repo, run bundle to install dependencies. Then, run rake spec to run the tests.

Contributing

Bug reports and pull requests are welcome on GitHub at amancevice/yake.

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

docker-superset

Docker image for Airbnb's Superset
Dockerfile
952
star
2

terraform-aws-slackbot

Serverless Extensible Slackbot
Python
84
star
3

docker-pandas

Base Docker image for Pandas installed on Debian/Alpine Linux
Makefile
53
star
4

terraform-aws-serverless-pypi

Serverless PyPI backed by S3
HCL
53
star
5

influxalchemy

Query InfluxDB using SQLAlchemy-style syntax
Python
50
star
6

terraform-aws-custom-ecr-domain

Set up a custom DNS entry for ECR
HCL
37
star
7

caravel

Docker image for AirBnB's Caravel
Python
35
star
8

rumrunner

Rake-based utility for building multi-stage Dockerfiles.
Ruby
34
star
9

redpanda

Pandas-SQLAlchemy integration
Python
28
star
10

flatsplode

Flatten/Explode JSON objects
Python
17
star
11

aws-sts-assume-role

GitHub Action to assume an AWS IAM role and export the credentials to ENV
JavaScript
16
star
12

python-lambda-gateway

Simple HTTP server to invoke a Lambda function locally
Python
15
star
13

nextcloud-heroku

Deploy nextcloud on heroku
Shell
14
star
14

fest

Sync public facebook page events to Google Calendar
Python
13
star
15

slackend

Simple asynchronous back end for Slack apps
JavaScript
12
star
16

docker-influxdb-cluster

Docker definiton for configurable InfluxDB node building
Shell
9
star
17

spin

Execute a command and display a scrolling block of logs
Shell
9
star
18

dip

Distribute CLIs using docker-compose
Python
8
star
19

lambda-compose

Developing Python applications for AWS Lambda
Makefile
6
star
20

terraform-aws-slackbot-slash-command

Generic slash command handler for Slack
Python
6
star
21

requests-iamauth

Use AWS SigV4 authorization with requests
Python
6
star
22

terraform-aws-group-sms

Send SMS messages to a group via AWS SNS
HCL
6
star
23

setup-code-climate

Setup Code Climate test reporter binary to use with your GitHub Actions workflows
JavaScript
5
star
24

pline

AWS Pipeline Wrapper for boto3
Python
5
star
25

knackhq

Python wrapper for KnackHQ API
Python
5
star
26

slack-drive

Manage sharing of Google Docs using Slack channels
JavaScript
5
star
27

envopt

Wrapper for docopt to allow ENV variables as argument defaults
Python
4
star
28

terraform-google-slack-events

Publish Slack events to Google Cloud Pub/Sub using Cloud Functions
HCL
3
star
29

terraform-aws-lambda-basic-execution-role

Lambda IAM role with AWSLambdaBasicExecution policy attached
HCL
2
star
30

python-lambo

Simple and visually pleasing logger for AWS Lambda
Python
2
star
31

terraform-aws-auth0-authorizer

Authorizer Lambda for API Gateway custom authorizers.
HCL
2
star
32

furi

Interact with local & remote files by URI
Python
2
star
33

language-pipfile

Pipfile syntax highlighting for Atom
1
star
34

the-good-docker-icon

That's it
1
star
35

terraform-aws-facebook-gcal-sync

Synchronize facebook page events with Google Calendar
HCL
1
star
36

terraform-aws-serverless-pypi-cognito

Basic auth for the serverless-pypi Terraform module using AWS Cognito
HCL
1
star
37

block-kit

Slack Block Kit Builder for Electron
JavaScript
1
star
38

slack-sms

Send SMS message from Slack slash commands
JavaScript
1
star
39

terraform-aws-express-lambda-layer

Lambda layer for express/aws-serverless-express
HCL
1
star
40

terraform-heroku-facebook-gcal-sync

Synchronize facebook page events with Google Calendar
HCL
1
star
41

icalendar-google

Google Calendar extension for iCalendar
Ruby
1
star
42

docker-fishshell

Lightweight docker image running the fishshell on ubuntu
Shell
1
star
43

finparse

Parse financial strings to number objects
Python
1
star
44

terraform-google-cloud-project

Terraform configuration for generic Google Cloud Project
HCL
1
star