Slide 1

Slide 1 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 24th Nov, 2021 見せてやるよ、Step Functions の本気ってやつをな @toricls AWS Expert Online JAWS-UG @afukui @_kensh

Slide 2

Slide 2 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Introduce our States. @toricls @afukui @_kensh Kensuke Shimokawa Snr. Serverless Specialist Atsushi Fukui Snr. Serverless Specialist Tori Hara Snr. Dev Advocate, Containers

Slide 3

Slide 3 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions を使っていますか?

Slide 4

Slide 4 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 本セッションは 想定される聴講者 • AWSをご利用されている事業者、デベロッパー • AWSを今後利用したビジネスを考えている方 • サーバーレスでの構築に興味がある方 ゴール • システムでの Step Functions の使い所を理解していただく

Slide 5

Slide 5 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions のかゆいところ

Slide 6

Slide 6 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. JSON (ASL) でワークフローを書くのが大変?

Slide 7

Slide 7 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. JSON (ASL) でワークフローを書くのが大変? { "StartAt": "Check Stock Price", "Comment": "An example of itegrating lambda functtions in Step Functions state machine.", "States": { "Check Stock Price": { "Type": "Task", "Resource": "", "Next": "Generate Buy/Sell recommendation" }, "Generate Buy/Sell recommendation": { "Type": "Task", "Resource": "", "ResultPath": "$.recommended_type", "Next": "Request Human Approval" }, "Request Human Approval": { "Type": "Task", "Resource": "arn::states:::sqs:sendMessage.waitForTaskToken", "Parameters": { "QueueUrl": "", "MessageBody": { "Input.$": "$", "TaskToken.$": "$$.Task.Token" } }, "ResultPath": null, "Next": "Buy or Sell?" }, "Buy or Sell?": { "Type": "Choice", "Choices": [ { "Variable": "$.recommended_type", "StringEquals": "buy", "Next": "Buy Stock" }, { "Variable": "$.recommended_type", "StringEquals": "sell", "Next": "Sell Stock" } ] }, "Buy Stock": { "Type": "Task",

Slide 8

Slide 8 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions Workflow Studio によるワークフローの構築 Workflow Studio は、ビジュアルツールを使用 してワークフローをより迅速に開発 https://aws.amazon.com/jp/blogs/news/new-aws-step-functions-workflow-studio-a-low-code-visual-tool-for-building-state-machines/ Data Science Amazon SageMaker Amazon EMR Amazon Athena Amazon Glue

Slide 9

Slide 9 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS Step Functions Data Science SDK による ワークフローの構築 AWS Step Functions Data Science SDK : Pythonで前処理 - 学習 - デプロイ のワークフローを構築 https://aws.amazon.com/jp/about-aws/whats-new/2019/11/introducing-aws-step-functions-data-science-sdk-amazon-sagemaker/ https://github.com/aws/amazon-sagemaker-examples/

Slide 10

Slide 10 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions が YAML のツールサポートを追加 • 一部ツールにおいてステートマシンの定義に YAML を使えるように • AWS Toolkit for Visual Studio Code, AWS CloudFormation でサポート AWS Toolkit for Visual Studio Code AWS CloudFormation JSON YAML

Slide 11

Slide 11 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. CDK Step Functions コンストラクトの利用 • @aws-cdk/aws-stepfunctions パッケージには、ワークフローを 構築するためのコンストラクトが 含まれています • @aws-cdk/aws-stepfunctions- tasksパッケージには、他のAWS サービスを呼び出すために使用さ れるクラスが含まれています (snip) const getStatus = new tasks.LambdaInvoke(this, 'Get Job Status', { lambdaFunction: getStatusLambda, // Pass just the field named "guid" into the Lambda, put the // Lambda's result in a field called "status" in the response inputPath: '$.guid', outputPath: '$.Payload', }); const definition = submitJob .next(waitX) .next(getStatus) .next(new sfn.Choice(this, 'Job Complete?') // Look at the "status" field .when(sfn.Condition.stringEquals('$.status', 'FAILED'), jobFailed) .when(sfn.Condition.stringEquals('$.status', 'SUCCEEDED'), finalStatus) .otherwise(waitX)); new sfn.StateMachine(this, 'StateMachine', { definition, timeout: Duration.minutes(5), });

Slide 12

Slide 12 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions から呼ばれる Lambda 関数のリポジトリ分け どうするのが正解?

Slide 13

Slide 13 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions から呼ばれる Lambda 関数のリポジトリ分け AWS Lambda AWS Lambda AWS Lambda AWS Lambda AWS CodeCommit どの単位でリポジトリに入れる?

Slide 14

Slide 14 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. ドメイン駆動設計 (Eric Evans - 2003) 設計における意思決定とドメイン設計 の議論における技術的な用語の広義の フレームワークを提供 ユビキタス言語 ビジネスドメインエキスパートと開発者の間の 意思疎通として利用される用語によってモデリ ングと設計を行う 戦略的な設計のためのガイドライン 境界づけられたコンテキストの考察

Slide 15

Slide 15 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 境界づけられたコンテキスト 境界づけられたコンテキストはユビ キタス言語によって設計されたモデ ルを適用できる限定された範囲 コンテキストの境界を定めることで 、チームメンバーは何を一致させる べきで何を独立して開発できるのか についての理解を明確化し、共有で きる https://www.martinfowler.com/bliki/BoundedContext.html Customer Ticket Product Product version Customer Product Territory Opportunity Pipeline Salesperson Defect Sales context Support context

Slide 16

Slide 16 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. コンテキストマップ Sales context Support context Marketing context 境界づけられたコンテキストだけでは、ドメインの 全体像を示すことはできない コンテキストマップは、境界づけられたコンテキスト を統合することにより、異なるが関連するユビキタス 言語のマッピングを処理する DDDでは境界づけられたコンテキストを統合するため の7つのパターンを説明 • 共有カーネル (Shared Kernel) • 顧客/供給者の開発チーム (Customer/Supplier Development Teams) • 順応者 (Conformist) • 腐敗防止層 (Anticorruption layer) • 別々の道 (Separate ways) • 公開ホストサービス (Open/Host service) • 公表された言語 (Published language)

Slide 17

Slide 17 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions から呼ばれる Lambda関数のデバッグは どうやれば良いか?

Slide 18

Slide 18 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. ビジネスロジックの配置 ReserveFlight Function CreateBooking Function ReserveHotel Function BookTrip Workflow 広範なスタックで構成された ビジネスロジック POST / HTTP/1.1 StartExecution 分散されたロジック ⼩さなスタックで Unit Test 完結 travelAgent.bookTrip() reserveFlight() reserveHotel() createBooking() TravelAgent::bookTrip() ローカルに配置されるロジック サーバーレス アプリケーション AWS Step Functions State Machine これまでのアプリケーション Class Method 入力バリデーション + データ変換 + ビジネスルール https://speakerdeck.com/_kensh/serverless-testing-2021?slide=43

Slide 19

Slide 19 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 広範なテストのために必要な変更 Business logic handler() Order Repository Business logic handler() Order Backlog test() assert() act() assert() Unit Tests Integration Tests Permissions untested Unit Tests Integration Tests Permissions untested Deploy to test Deploy to test

Slide 20

Slide 20 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions の入出力処理 (JSON path syntax) どうやって慣れる?

Slide 21

Slide 21 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions の入出力処理 https://docs.aws.amazon.com/step-functions/latest/dg/concepts-input-output-filtering.html • InputPath では、Task 状態 のタスクにどの JSON 入力 部分を渡すかを選択 • ResultPath を使用して、出 力に渡す状態入力とタスク 結果の組み合わせを選択 • OutputPath では、JSON 出 力をフィルタリングして、 出力に渡される情報を絞り 込む

Slide 22

Slide 22 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Data flow simulator 各Stateは、JSONを受け取 り、出力としてJSONを次 の状態に渡します • データが状態から状態へとど のように流れるかを理解する • データをフィルタリングおよ び操作する方法を学ぶ

Slide 23

Slide 23 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. builders.flash https://aws.amazon.com/jp/builders-flash/202104/stepfunctions-fizzbuzz

Slide 24

Slide 24 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions にまつわる 学校で友達に自慢したくなること

Slide 25

Slide 25 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions で 復元力のあるAWS Fargate Task 実行って?

Slide 26

Slide 26 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS Fargate with Step Functions 3. Fargate Task の「stoppedReason」 に基づく詳細なエラー処理 2. 並列化された Fargate Task 1. 復元力のあるスケジュールされた Fargate Task 「リトライ」機能を使用 Map State を使用して、パラメータ化された Fargate Task を実行 エラーが ResourceInitializationError の場合は再試行 CannotPullContainerError の場合は失敗 https://github.com/toricls/aws-fargate-with-step-functions

Slide 27

Slide 27 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. オンプレミスのジョブとどうやって連携する?

Slide 28

Slide 28 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Callback ワークフロー AWS Step Functions workflow Start Notify End ワークフロー Job Notify Event (time-based) オンプレミス サーバー Queue Lambda function Token, Param Token, Result OR Tokenを外部サービスに連携して、 コールバック待機可能 Amazon Elastic Container Service (Amazon ECS) https://docs.aws.amazon.com/ja_jp/step-functions/latest/dg/callback-task-sample-sqs.html

Slide 29

Slide 29 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 並列ジョブをどうやって実装する?

Slide 30

Slide 30 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda 関数ジョブの並列化 with Map AWS Step Functions workflow Start End ワークフロー Transform Load Event (time-based) S3 Extract function Transform function Load function Transform Load Extract Transform Load Map Lambda関数でのETLを Map State により並列化 [data1, data2, …, dataN] https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states- language-map-state.html

Slide 31

Slide 31 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step FunctionsをAPI処理に使える?

Slide 32

Slide 32 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 軽量 ETL オーケストレーション として使う AWS Step Functions workflow Start Extract End ワークフロー Transform Load Amazon API Gateway より軽量で短時間なETL処理であれば、 API Gateway から同期的にワークフローをコールする ことも可能

Slide 33

Slide 33 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. BFF(Backends For Frontends)として使う AWS Step Functions workflow Start API End ワークフロー API API Amazon API Gateway API Gatewayから同期的に Express ワークフローを コールする Mobile client オンプレミス サーバー Lambda function Amazon Elastic Container Service (Amazon ECS) BFF

Slide 34

Slide 34 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 非同期パターン として使う with WebSockets サーバーからクライアントへ WebSockets による通知を 行い、 よりタイムリーに実行結果を送信 Step Functions workflow onConnect API Gateway (WebSockets) Step Functions Lambda API Gateway Mobile client https://aws.amazon.com/blogs/compute/from-poll-to-push-transform-apis-using-amazon-api-gateway-rest-apis-and-websockets/ API Gatewayから非同期にワークフローを 実行する Amazon DynamoDB

Slide 35

Slide 35 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. デザインパターンの視点を考えたい

Slide 36

Slide 36 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 自律的に処理をコントロールするには?

Slide 37

Slide 37 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. コレオグラフィーパターンとは • 必要なすべての情報を含んだ最初のイベントを 1 つのメッセージに保存し て、最初のトランザクションを完了 • 他のサービスがそのメッセージを非同期的に取得し、それぞれのタスクを 完了させる • サービスが疎結合になり、直接互いに影響を与えない • メッセージの保存と取得が非同期の関係になり、スケーラビリティと信頼 性が向上

Slide 38

Slide 38 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. コレオグラフィーパターン ユーザー リクエストサービス リクエストキュー サービスA サービスB サービスC

Slide 39

Slide 39 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 実装例1: SNS、 SQS、 Lambdaの利用 ユーザー リクエストサービス Amazon SNS Amazon SQS Amazon SQS Amazon SQS AWS Lambda AWS Lambda AWS Lambda ファンアウト

Slide 40

Slide 40 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 実装例2: Amazon EventBridgeの利用 配送 ポイント プレミアム会員 カート 支払 支払い方法 認証 注文 1分毎に実行 Events 会員 ステータス 支払認証 カートに 入れる 注文完了 Amazon EventBridge リクエストサービス イベントバス

Slide 41

Slide 41 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 中央で処理をコントロールするには?

Slide 42

Slide 42 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. コレオグラフィーとオーケストレーション ユーザー リクエストサービス リクエストキュー サービスA サービスB サービスC サービスA サービスB サービスC ユーザー リクエストサービス Step Functions workflow

Slide 43

Slide 43 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. オーケストレーション ⼝座申請 ⼝座 データ チェック ⼈による 確認 IDをチェック アドレスのチェック ⼈による確認 ⼝座の作成 1つのプロセスがワークフローの状態を管理し、 適切なサービスを順番に呼び出す Step Functions で実装可能

Slide 44

Slide 44 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 長期トランザクションを管理するには?

Slide 45

Slide 45 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Sagaパターン • ”Saga内のトランザクションは相互に関連しており、(非アトミックな)ユニット として実行する必要がある。Sagaの部分的な実行は望ましくなく、エラーが発生 した場合は補償する必要がある。” • 部分的な実行を修正するには、各SagaトランザクションT(i)に補償 トランザクションC(i)を提供する必要がある。 • 補償トランザクションは、セマンティックの観点から、T(i)によって実行されたア クションをすべて元に戻すが、(他のトランザクションによって変更されている可 能性があるため)データベースをT(i)の実行が開始されたときに存在していた 状態に戻すとは限らない。

Slide 46

Slide 46 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Sagaの実装 • アプリケーションプログラマの観点からは、Sagaの開始と終了、各トランザク ションの開始と終了、および補償トランザクションをシステムに知らせるため のメカニズムが必要 • SagaトランザクションIDや補償トランザクションの名前、エントリポイント、 補償トランザクションに必要なパラメータ、セーブポイントなどを保持する必 要がある

Slide 47

Slide 47 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Sagaの実装(バックワードリカバリ)

Slide 48

Slide 48 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Sagaの実装 (フォワードリカバリとSave Point) 注意:常に可能であるとは限らない

Slide 49

Slide 49 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Sagaと並列トランザクション • Sagaは並列トランザクションを含むように拡張することが可能 • 並列Sagaの各プロセス内で、トランザクションはシーケンシャルなSagaと同様 に逆の順序で補償 • 子プロセスのすべての補償は、子プロセスの作成前に実行された 親トランザクションの補償の前に発生する必要がある

Slide 50

Slide 50 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. マイクロサービスアーキテクチャと共に再び注目 • Chris RichardsonがMicroservices PatternsでSagaパターンを取り上げたこと で再び注目を浴びる(*) • Pattern: Saga (**) • マイクロサービスで典型的な Database per Serviceパターンを適用している 場合、個々のマイクロサービス内ではACIDトランザクションを利用出来る が、サービスをまたがるトランザクションを管理する仕組みが必要 • => Sagaパターン • 実装例としてコレオグラフィベースのSagaとオーケストレーションベースの Sagaを紹介 (*) https://microservices.io/index.html (**) https://microservices.io/patterns/data/saga.html

Slide 51

Slide 51 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions による Saga パターンの実装 https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-the-serverless-saga-pattern-by-using-aws-step-functions.html このパターンは、図で強調表示されている タスクごとに Lambda関数と、3つの DynamoDBテーブルをデプロイします。 各Lambda関数は、トランザクションがコ ミットされたかロールバックされたかに応 じて、対応するDynamoDBテーブルのitem を作成、更新、削除します。 Amazon SNSを使用してテキスト(SMS) メッセージをサブスクライバーに送信し、 トランザクションの失敗または成功を通知

Slide 52

Slide 52 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. コードフリーな世界観に浸りたい

Slide 53

Slide 53 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Step Functions が AWS SDK との統合をサポート AWS Step Functions Express Workflows Start End GetSampleVideo GetTranscriptionText • 200+のサービス、9000+の API アクションを新たにサポート • カスタムコードの記述不要で、SDK で 提供されている API を呼び出せる • ASL 組み込み関数を使って データを変換することができる • ほとんの場合 IAM ポリシーは自動生成 されないので、明示的に追加する必要 がある ポイント AWS SDK サポートされているサービス一覧 https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html StartTextTranslation StartTranscriptionJob Amazon Transcribe Amazon Translate s3:copyObject transcribe:startTranscriptionJob s3:getObject translate:translateText

Slide 54

Slide 54 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. EventBridge のターゲットに 新機能 API Destinations を指定可能に ポイント • 任意のエンドポイントに対して HTTPリクエストを送ることができる • コードの実装は不要 • 3種類の認証タイプ (Basic認証 / OAuth クライアントクレデンシャル / API キー) を利用可能。クレデンシャルは AWS Secrets Manager で管理。 • 入力値のカスタマイズやリトライ、 呼び出しレートの調整も可能

Slide 55

Slide 55 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Slide 56

Slide 56 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. まとめ • Step Functions はサーバーレスなワークフローであり、ご利用した分の課金 になります。 • マイクロサービスをオーケストレーションしたい場合、Step Functions で処 理を制御することにより、可視化されたワークフローを体験できます。 • サーバーレスサービスの中でも特に進化の早いサービスの一つとなってお り、多くのユースケースで使われています。

Slide 57

Slide 57 text

@_kensh

Slide 58

Slide 58 text

© 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Thank you! @toricls @afukui @_kensh