AWS Lambda + Kotlin -> Redirector

しらじ(shiraji)
ASICS Digital
Published in
14 min readSep 20, 2017

Hi, my name is Yoshi. I work for ASICS’s digital and innovation. I joined ASICS, Inc in May, 2017.

Today, I want to introduce our new redirector (haven’t released it, yet, since we have a lot of services!).

Apology if this article is too old. I wrote this entry in July 2017.

Prerequisite

  • Basic knowledge of Kotlin, Redirector, AWS Lambda/Gateway, HTTP protocol

Summary of the task

  • Redirect based on HTTP request
  • Status code can be 301, 302, or 5xx
  • Adding location header is required for 301 and 302

AWS Lambda

The reason why we pick AWS Lambda is followings:

  • ASICS and Runkeeper uses AWS in a lot of services
  • AWS Lambda accepts multiple computer languages
  • Huge size of free tier💰

Language

The previous version of the redirector was written in Node.js. So, we can just copy and paste the code and task can be done! However, I don’t see any test codes in the project. Also, we want to change some sort of features of the redirector, which I won’t explain here😉. Therefore, I decided to reimplement the redirector in Kotlin. The following the reason why I pick Kotlin.

  • Runkeeper Engineers mainly use Java and interested to use Kotlin
  • AWS Lambda accepts Java (=Kotlin)
  • Easy to write unit tests
  • AWS Lambda + Java (=Kotlin) is slow at the first request but it doesn’t matter for redirector which is running months without rebooting
  • I am one of Kotlin contributors💪

Create Kotlin project

Create Kotlin project using Intellij. Here is the build.gradle

And then, create a class that AWS Lambda calls. There are some ways to implement this function. In this project, I selected RequestStreamHandler as its interface. I would suggest that whenever you want to change the response header using AWS Gateway+Lambda, you should use this class. I tried RequestHandler and other ways to implement this and wasted a few business days😢

Here is the documentation of request and response information

Based on the documentation, I created a simple class that gets request data from InputStream, convert request data to response data and return response data using OutputStream.

ResponseData class and RequestData class are following. I used Gson to serialize/deserialize JSON.

Output JSON would be the following, when this program wants to redirect with 301 status.

You can take a look for whole project here

In order to create a zip file that will be used later, Run ./gradlew clean build

Setup AWS Lambda

The best source would be official documentation. However, even though they provide GUI, the documentation does not use a lot of images. So, I will explain using images based on July 2017 web pages.

  • Go to AWS Lambda’s list of functions page.
  • Click “Create a Lambda Function” button

Next page would be selecting blueprint, in this example click “Blank Function”

It goes to Configure function page. Most of the setting on this page can be modified later. As a default setting, Node.js 6.10 is selected. Change that to Java8

  • Upload zip file which you created above
  • The handler name is ${package.name}.${class.name}::${method.name} In this example, com.github.shiraji.Redirector::handleRequest

Setting AWS Gateway

Just follow what AWS document

Don’t forget selecting “Use Lambda Proxy Integration”

After deploying AWS Gateway, you can run curl command

That’s it!💯

Summary

This is the first server side Kotlin project for me, but because AWS Gateway+Lambda is easy to use, I can develop this redirector smoothly. I would definitely try AWS Lambda when I need to implement light-weight API server.

ASICS Corporation

Since its founding in 1949, ASICS Group has been committed to nurturing the world’s youth through sports in order to contribute to society.
Our vision has been to “Create Quality Lifestyle through Intelligent Sport Technology” and our mission to provide goods and services that promote healthy and fulfilling lifestyles throughout the world.

If you are passionate to work with us, please contact us by sending email: ahq-digital@asics.com

ASICSのデジタルを触っています。2017年5月に入社したばかりの新人の磯貝です。以後よろしくお願いいたします。🙇

それではいきなりですが、弊社のRedirectorの実装を変えましたので、そのことについて書きたいと思います。リリースは影響度が大きいため、順次していく予定です。

この記事は2017年7月に書きました。古くなっている可能性もあります。ご了承下さい。

前提条件

  • Kotlin, Redirectorの説明はしません
  • AWS Lambda/Gatewayが何者なのかを知っている
  • HTTP通信の基礎的な知識がある

概要

ASICSのRedirectorが古いので、移行しようぜ!👊ということから対応することになりました。ASICSに入社してから初めてのタスクでした💐

必要条件

  • URLごとにリダイレクトする
  • ステータスコードは301, 302, 5xx
  • Locationヘッダーを301, 302の時に追加する

AWS Lambda

AWS Lambdaを選択した理由として

  • ASICSとRunkeeperの多くのサービスでAWSを使っていた
  • AWS Lambdaが複数言語を利用できる
  • 無料枠がデカい💰

言語

今までのRedirectorはnode.jsで書かれており、それをそのままコピペするで良かったのですが、テストコードもなく、今後修正する可能性が高かったため、再開発することに決めました。

Kotlinを採用した理由は以下です。

  • RunkeeperではJavaがメインで利用されていること
  • AWS LambdaでJavaが使えたこと
  • Unitテストが書きやすいこと
  • Javaは初回起動が遅いが、長時間利用されるため問題なかったこと
  • 自分が担当だったこと💪

Kotlinプロジェクトを作る

まずはIntellijでKotlinのプロジェクトを作成します。build.gradleはこんな感じです。

次にLambdaが呼び出すコードを作成します。いくつか方法がありますが、今回はレスポンスをカスタマイズしたいため、RequestStreamHandlerを採用します。個人的な意見ですが、ヘッダーなどレスポンスをイジるのであれば、RequestStreamHandler一択だと思います。私は古い情報に惑わされ、2,3日無駄にしました😢

Request/Responseデータのドキュメントはこちらです。

これをベースにRequest/ResponseデータはGsonを利用してクラスを作成しました。

301にしたい場合、こんな感じのJSONが出来上がります。

まとめたプロジェクトはここに置いてあります。

ビルド方法は./gradlew clean buildです。zipファイルが出来ます。

これでコーディングは終わりです。楽勝ですね 🙈

AWS Lambdaの設定をする

ドキュメントを参考にする方が良いのですが、GUIの設定なのに、文字しかなく混乱したので、2017年7月時点のUIで説明します。

AWS LambdaのダッシュボードかFunctions一覧に遷移し、Create a Lambda Functionボタンをクリックします。

テンプレートの設定画面になりますが、今回はBlank Functionを選択します。

Functionの設定画面に遷移します。node.jsがデフォルトで設定されていますので、それをJava8にします。

Kotlinプロジェクトをビルドして出来たzipモジュールをUploadします。

Handlerのフォーマットはパッケージ名.クラス名::メソッド名です。今回のコードの場合、com.github.shiraji.Redirector::handleRequestとなります。このあたりは全て後で変更することも可能です。

AWS Gatewayの設定

ドキュメントに則り進めるのが良いです。

Use Lambda Proxy Integrationのチェックは忘れずにつけて下さい。

AWS Gatewayをdeployした後、curlコマンドを実行してみるとこのような結果になります。

これで完了です💯

感想

サーバサイドKotlinを初めて挑戦してみましたが、非常にスムーズに開発が出来ました。AWS Gateway+Lambdaのお手軽さがよかったです。簡単なAPIサーバならこれで対応しちゃうと良いと感じました。

株式会社アシックス

アシックスグループは、スポーツによる青少年の育成を通じて社会の発展に貢献したいという思いから始まりました。
私たちはその創業の精神を受け継ぎ、60年以上にわたり独自の製品とサービスを提供し、現在ではトップアスリートはもとより一般のユーザーまで幅広いお客様より信頼をいただいています。
海外売上比率が80%を超え、世界中でご愛用いただけるグローバルな企業へと進化してきました。

私たちとぜひ一緒に働いてみませんか?興味のある方は ahq-digital@asics.com にメールを送って下さい。

--

--

しらじ(shiraji)
ASICS Digital

Android/Java/Kotlin/GradleライブラリやIntelliJプラグイン作ってます。いきなりPR投げつけていきます。