Upgrade to Pro — share decks privately, control downloads, hide ads and more …

見せてやるよ、Step Functions の本気ってやつをな / The art of Step Functions

kensh
November 24, 2021

見せてやるよ、Step Functions の本気ってやつをな / The art of Step Functions

動画はこちら
https://www.youtube.com/watch?v=DcE_c8_6QUk

見せてやるよ、Step Functions の本気ってやつをな / The art of Step Functions

kensh

November 24, 2021
Tweet

More Decks by kensh

Other Decks in Technology

Transcript

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

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

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

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

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

    rights reserved. JSON (ASL) でワークフローを書くのが大変?
  7. © 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": "<CHECK_STOCK_PRICE_LAMBDA_ARN>", "Next": "Generate Buy/Sell recommendation" }, "Generate Buy/Sell recommendation": { "Type": "Task", "Resource": "<GENERATE_BUY_SELL_RECOMMENDATION_LAMBDA_ARN>", "ResultPath": "$.recommended_type", "Next": "Request Human Approval" }, "Request Human Approval": { "Type": "Task", "Resource": "arn:<PARTITION>:states:::sqs:sendMessage.waitForTaskToken", "Parameters": { "QueueUrl": "<REQUEST_HUMAN_APPROVAL_SQS_URL>", "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",
  8. © 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
  9. © 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/
  10. © 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
  11. © 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), });
  12. © 2021, Amazon Web Services, Inc. or its Affiliates. All

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

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

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

    rights reserved. Step Functions から呼ばれる Lambda関数のデバッグは どうやれば良いか?
  18. © 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
  19. © 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
  20. © 2021, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Step Functions の入出力処理 (JSON path syntax) どうやって慣れる?
  21. © 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 出 力をフィルタリングして、 出力に渡される情報を絞り 込む
  22. © 2021, Amazon Web Services, Inc. or its Affiliates. All

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

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

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

    rights reserved. Step Functions で 復元力のあるAWS Fargate Task 実行って?
  26. © 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
  27. © 2021, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. オンプレミスのジョブとどうやって連携する?
  28. © 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
  29. © 2021, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. 並列ジョブをどうやって実装する?
  30. © 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
  31. © 2021, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Step FunctionsをAPI処理に使える?
  32. © 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 から同期的にワークフローをコールする ことも可能
  33. © 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
  34. © 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
  35. © 2021, Amazon Web Services, Inc. or its Affiliates. All

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

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

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

    rights reserved. コレオグラフィーパターン ユーザー リクエストサービス リクエストキュー サービスA サービスB サービスC
  39. © 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 ファンアウト
  40. © 2021, Amazon Web Services, Inc. or its Affiliates. All

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

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

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

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

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

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

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

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

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

    rights reserved. Sagaと並列トランザクション • Sagaは並列トランザクションを含むように拡張することが可能 • 並列Sagaの各プロセス内で、トランザクションはシーケンシャルなSagaと同様 に逆の順序で補償 • 子プロセスのすべての補償は、子プロセスの作成前に実行された 親トランザクションの補償の前に発生する必要がある
  50. © 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
  51. © 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) メッセージをサブスクライバーに送信し、 トランザクションの失敗または成功を通知
  52. © 2021, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. コードフリーな世界観に浸りたい
  53. © 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
  54. © 2021, Amazon Web Services, Inc. or its Affiliates. All

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

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

    rights reserved. Thank you! @toricls @afukui @_kensh