Step Functions
AWS Step Functionsは、分散アプリケーションを調整するためのサーバーレスワークフローオーケストレーションを提供します。MBC CQRS Serverlessフレームワークでは、Step Functionsは以下の目的で使用されます:
- 長時間実行ワークフローのオーケストレーション
- 分散トランザクションのためのSagaパターン実装
- Distributed Mapを使用した並列バッチ処理
- コールバックパターンを使用した非同期タスク調整
アーキテクチャ概要
ステートマシン
フレームワークは3つの事前設定済みステートマシンを提供します:
コマンドステートマシン
バージョン管理と並列処理を伴うデータ同期ワークフローを処理します。
主な機能:
- バージョンチェック:コマンドの順序を保証し、競合を防止
- 非同期コールバック:タスクトークンを使用して前のコマンドを待機
- 並列同期:Map状態を使用して複数のターゲットにデータを同期
- TTL管理:レコードの有効期限を自動設定
タスクステートマシン
制御された並行性で並列サブタスクを実行します。
主な機能:
- 制御された並行性:並列実行を制限(デフォルト:2)
- ステータス追跡:リアルタイムのタスクステータス更新
- エラーハンドリング:自動的な障害検出とレポート
CSVインポートステートマシン
AWS Distributed Mapを使用して大規模なCSVファイルを大規模並列処理します。
主な機能:
- S3ネイティブ統合:S3から直接CSVを読み取り
- バッチ処理:効率的な処理のために行をグループ化
- 高並行性:最大50の同時バッチプロセッ サをサポート
- EXPRESS実行:子ステートマシンにExpressワークフローを使用
システム構成例
以下の図は、一般的な本番環境でStep FunctionsがどのようにAWSサービスと統合されるかを示しています:
データフローの例
Step Functionsを使用したコマンド実行の一般的なデータフローは以下の通りです:
CDK実装例
完全なコマンドステートマシン
以下のCDKコードは、完全なコマンドハンドラーステートマシンの作成方法を示しています:
import * as cdk from 'aws-cdk-lib';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';
import * as tasks from 'aws-cdk-lib/aws-stepfunctions-tasks';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as logs from 'aws-cdk-lib/aws-logs';
import { Construct } from 'constructs';
export class CommandStateMachineConstruct extends Construct {
public readonly stateMachine: sfn.StateMachine;
constructor(scope: Construct, id: string, props: { lambdaFunction: lambda.IFunction }) {
super(scope, id);
const { lambdaFunction } = props;
// Lambda呼び出しタスクを作成するヘルパー関数
const createLambdaTask = (
stateName: string,
integrationPattern: sfn.IntegrationPattern = sfn.IntegrationPattern.REQUEST_RESPONSE
) => {
const payload: Record<string, any> = {
'source': 'step-function',
'context.$': '$$',
'input.$': '$',
};
// コールバックパターン用タスクトークンを追加
if (integrationPattern === sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN) {
payload['taskToken'] = sfn.JsonPath.taskToken;
}
return new tasks.LambdaInvoke(this, stateName, {
lambdaFunction,
payload: sfn.TaskInput.fromObject(payload),
stateName,
outputPath: '$.Payload[0][0]',
integrationPattern,
retryOnServiceExceptions: true,
});
};
// ステートを定義
const fail = new sfn.Fail(this, 'fail', {
stateName: 'fail',
causePath: '$.cause',
errorPath: '$.error',
});
const success = new sfn.Succeed(this, 'success', {
stateName: 'success',
});
// タスクステートを作成
const finish = createLambdaTask('finish').next(success);
const syncData = createLambdaTask('sync_data');
// 並列データ同期のマップステート
const syncDataAll = new sfn.Map(this, 'sync_data_all', {
stateName: 'sync_data_all',
maxConcurrency: 0, // 同時実行数無制限
itemsPath: sfn.JsonPath.stringAt('$'),
})
.itemProcessor(syncData)
.next(finish);
const transformData = createLambdaTask('transform_data').next(syncDataAll);
const historyCopy = createLambdaTask('history_copy').next(transformData);
const setTtlCommand = createLambdaTask('set_ttl_command').next(historyCopy);
// 前のコマンド待機のコールバック パターン
const waitPrevCommand = createLambdaTask(
'wait_prev_command',
sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN
).next(setTtlCommand);
// バージョンチェックの選択ステート
const checkVersionResult = new sfn.Choice(this, 'check_version_result', {
stateName: 'check_version_result',
})
.when(sfn.Condition.numberEquals('$.result', 0), setTtlCommand)
.when(sfn.Condition.numberEquals('$.result', 1), waitPrevCommand)
.when(sfn.Condition.numberEquals('$.result', -1), fail)
.otherwise(waitPrevCommand);
const checkVersion = createLambdaTask('check_version').next(checkVersionResult);
// ロググループを作成
const logGroup = new logs.LogGroup(this, 'StateMachineLogGroup', {
logGroupName: '/aws/vendedlogs/states/command-handler-logs',
removalPolicy: cdk.RemovalPolicy.DESTROY,
retention: logs.RetentionDays.SIX_MONTHS,
});
// ステートマシンを作成
this.stateMachine = new sfn.StateMachine(this, 'CommandHandlerStateMachine', {
stateMachineName: 'command-handler',
comment: 'Handles command stream processing with version control',
definitionBody: sfn.DefinitionBody.fromChainable(checkVersion),
tracingEnabled: true,
logs: {
destination: logGroup,
level: sfn.LogLevel.ALL,
},
});
}
}
制御された並行性を持つタスクステートマシン
export class TaskStateMachineConstruct extends Construct {
public readonly stateMachine: sfn.StateMachine;
constructor(scope: Construct, id: string, props: { lambdaFunction: lambda.IFunction }) {
super(scope, id);
const { lambdaFunction } = props;
// 各アイテムのイテレータータスク
const iteratorTask = new tasks.LambdaInvoke(this, 'iterator', {
lambdaFunction,
payload: sfn.TaskInput.fromObject({
'source': 'step-function',
'context.$': '$$',
'input.$': '$',
}),
stateName: 'iterator',
outputPath: '$.Payload[0][0]',
});
// 同時実行制限付きマップステート
const mapState = new sfn.Map(this, 'TaskMapState', {
stateName: 'map_state',
maxConcurrency: 2, // 一度に2アイテムを処理
inputPath: '$',
itemsPath: sfn.JsonPath.stringAt('$'),
}).itemProcessor(iteratorTask);
// ロググループを作成
const logGroup = new logs.LogGroup(this, 'TaskLogGroup', {
logGroupName: '/aws/vendedlogs/states/task-handler-logs',
removalPolicy: cdk.RemovalPolicy.DESTROY,
retention: logs.RetentionDays.SIX_MONTHS,
});
// ステートマシンを作成
this.stateMachine = new sfn.StateMachine(this, 'TaskHandlerStateMachine', {
stateMachineName: 'task-handler',
comment: 'Handles parallel task execution with concurrency control',
definitionBody: sfn.DefinitionBody.fromChainable(mapState),
timeout: cdk.Duration.minutes(15),
tracingEnabled: true,
logs: {
destination: logGroup,
level: sfn.LogLevel.ALL,
},
});
}
}
CSVインポート用のDistributed Map
大規模CSVファイルの処理には、ネイティブS3統合を提供するDistributed Mapを使用します:
import { Map as SfnMap, ProcessorMode, ProcessorConfig, IChainable, JsonPath } from 'aws-cdk-lib/aws-stepfunctions';
// Types for Distributed Map S3 item reader configuration (分散マップS3アイテムリーダー設定の型定義)
interface DistributedMapItemReader {
Resource: string;
ReaderConfig?: {
InputType: 'CSV' | 'JSON' | 'MANIFEST';
CSVHeaderLocation?: 'FIRST_ROW' | 'GIVEN';
CSVHeaders?: string[];
MaxItems?: number;
};
Parameters?: Record<string, string>;
}
// Types for Distributed Map batch processing configuration (分散マップバッチ処理設定の型定義)
interface DistributedMapItemBatcher {
MaxInputBytesPerBatch?: number;
MaxItemsPerBatch?: number;
BatchInput?: Record<string, string>;
}
// S3 CSV処理用カスタム分散マップクラス
export class DistributedMap extends SfnMap {
public itemReader?: DistributedMapItemReader;
public itemBatcher?: DistributedMapItemBatcher;
public label?: string;
public override toStateJson(): object {
const mapStateJson = super.toStateJson();
return {
...mapStateJson,
ItemReader: this.itemReader,
ItemBatcher: this.itemBatcher,
Label: this.label,
};
}
public itemProcessor(processor: IChainable, config: ProcessorConfig = {}): DistributedMap {
super.itemProcessor(processor, {
...config,
mode: ProcessorMode.DISTRIBUTED,
});
return this;
}
public setItemReader(itemReader: DistributedMapItemReader): DistributedMap {
this.itemReader = itemReader;
return this;
}
public setItemBatcher(itemBatcher: DistributedMapItemBatcher): DistributedMap {
this.itemBatcher = itemBatcher;
return this;
}
public setLabel(label: string): DistributedMap {
this.label = label;
return this;
}
}
// スタックでの使用法
const csvRowsHandler = new tasks.LambdaInvoke(this, 'csv_rows_handler', {
lambdaFunction,
payload: sfn.TaskInput.fromObject({
'source': 'step-function',
'context.$': '$$',
'input.$': '$',
}),
stateName: 'csv_rows_handler',
});
const importCsvDefinition = new DistributedMap(this, 'import-csv', {
maxConcurrency: 50, // 最大50バッチを並行処理
})
.setLabel('import-csv')
.setItemReader({
Resource: 'arn:aws:states:::s3:getObject',
ReaderConfig: {
InputType: 'CSV',
CSVHeaderLocation: 'FIRST_ROW',
},
Parameters: {
'Bucket.$': '$.bucket',
'Key.$': '$.key',
},
})
.setItemBatcher({
MaxInputBytesPerBatch: 10,
BatchInput: {
'Attributes.$': '$',
},
})
.itemProcessor(csvRowsHandler, {
executionType: sfn.ProcessorType.EXPRESS, // 子実行にはEXPRESSを使用
});
const importCsvStateMachine = new sfn.StateMachine(this, 'ImportCsvStateMachine', {
stateMachineName: 'import-csv',
comment: 'Processes large CSV files with distributed batch processing',
definitionBody: sfn.DefinitionBody.fromChainable(importCsvDefinition),
tracingEnabled: true,
});
イベントソース設定
DynamoDB StreamsとSQSを設定してStep Functionsをトリガーします:
// DynamoDBストリームイベントソース
const tableNames = ['tasks', 'commands', 'import_tmp'];
for (const tableName of tableNames) {
const table = dynamodb.Table.fromTableAttributes(this, `${tableName}-table`, {
tableArn: `arn:aws:dynamodb:${region}:${account}:table/${prefix}${tableName}`,
tableStreamArn: `arn:aws:dynamodb:${region}:${account}:table/${prefix}${tableName}/stream/*`,
});
lambdaFunction.addEventSource(
new lambdaEventSources.DynamoEventSource(table, {
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
batchSize: 1,
filters: [
lambda.FilterCriteria.filter({
eventName: lambda.FilterRule.isEqual('INSERT'),
}),
],
})
);
}
// SQSイベントソース
const queues = ['task-action-queue', 'notification-queue', 'import-action-queue'];
for (const queueName of queues) {
const queue = sqs.Queue.fromQueueArn(
this,
queueName,
`arn:aws:sqs:${region}:${account}:${prefix}${queueName}`
);
lambdaFunction.addEventSource(
new lambdaEventSources.SqsEventSource(queue, {
batchSize: 1,
})
);
}
実装ガイド
ステップ1:インフラストラクチャのセットアップ
フレームワークはAWS CDKを使用してStep Functionsインフラストラクチャを自動的にプロビジョニングします。主要なリソースは以下の通りです:
// CDKでのステートマシン定義
const commandStateMachine = new sfn.StateMachine(this, 'CommandHandler', {
stateMachineName: 'command',
definitionBody: sfn.DefinitionBody.fromChainable(definition),
timeout: Duration.minutes(15),
tracingEnabled: true,
logs: {
destination: logGroup,
level: sfn.LogLevel.ALL,
},
});
ステップ2:Step Functionイベントの定義
基本のStep Functionイベントを拡張するイベントクラスを作成します:
import { IEvent } from '@mbc-cqrs-serverless/core';
import { StepFunctionsContext } from '@mbc-cqrs-serverless/core';
export class CustomWorkflowEvent implements IEvent {
source: string;
context: StepFunctionsContext;
input?: WorkflowInput;
taskToken?: string;
}
ステップ3:イベントハンドラーの実装
Step Functionイベントを処理するハンドラーを作成します:
import { EventHandler, IEventHandler, StepFunctionStateInput } from '@mbc-cqrs-serverless/core';
import { Logger } from '@nestjs/common';
@EventHandler(CustomWorkflowEvent)
export class CustomWorkflowHandler implements IEventHandler<CustomWorkflowEvent> {
private readonly logger = new Logger(CustomWorkflowHandler.name);
async execute(event: CustomWorkflowEvent): Promise<StepFunctionStateInput> {
const stateName = event.context.State.Name;
switch (stateName) {
case 'initialize':
return this.handleInitialize(event);
case 'process':
return this.handleProcess(event);
case 'finalize':
return this.handleFinalize(event);
default:
throw new Error(`Unknown state: ${stateName}`);
}
}
private async handleInitialize(event: CustomWorkflowEvent) {
// 初期化ロジック
return { status: 'initialized', data: event.input };
}
private async handleProcess(event: CustomWorkflowEvent) {
// 処理ロジック
return { status: 'processed' };
}
private async handleFinalize(event: CustomWorkflowEvent) {
// 終了ロジック
return { status: 'completed' };
}
}
ステップ4:イベントファクトリーの設定
イベントファクトリーにStep Functionイベントを登録します:
import { EventFactory, IEvent, StepFunctionsEvent } from '@mbc-cqrs-serverless/core';
@EventFactory()
export class CustomEventFactory {
async transformStepFunction(event: StepFunctionsEvent<any>): Promise<IEvent[]> {
const stateMachineName = event.context.StateMachine.Name;
if (stateMachineName.includes('custom-workflow')) {
return [new CustomWorkflowEvent(event)];
}
return [];
}
}
ステップ5:ステートマシン実行のトリガー
サービスからステートマシン実行を開始します:
import { StepFunctionService } from '@mbc-cqrs-serverless/core';
import { Injectable } from '@nestjs/common';
@Injectable()
export class WorkflowService {
constructor(private readonly sfnService: StepFunctionService) {}
async startWorkflow(input: WorkflowInput): Promise<string> {
const executionArn = await this.sfnService.startExecution({
stateMachineArn: process.env.WORKFLOW_STATE_MACHINE_ARN,
input: JSON.stringify(input),
name: `workflow-${Date.now()}`,
});
return executionArn;
}
}
ユースケース
ユースケース1:データ同期
バージョン管理と競合解決を伴う複数テーブル間のデータ同期。
シナリオ: コマンドが作成されると、データを複数のリー ドモデルに同期します。
// トリガー: DynamoDBストリームINSERTイベント
// フロー: check_version -> set_ttl -> history_copy -> transform -> sync_all -> finish
await this.commandService.publishAsync(
{
pk: 'ORDER#tenant1',
sk: 'ORDER#order123',
id: 'order-uuid',
code: 'order123',
name: 'Order',
type: 'ORDER',
version: 1,
tenantCode: 'tenant1',
attributes: { status: 'confirmed', total: 1000 },
},
{ invokeContext },
);
// これにより自動的にコマンドステートマシンがトリガーされる
ユースケース2:バッチタスク処理
制御された並行性で複数の関連タスクを並列実行します。
シナリオ: ステータス追跡を伴うバッチジョブで複数のアイテムを処理します。
// タスクステートマシンで処理されるタスクを作成
const items = [
{ itemId: 'item1', action: 'process' },
{ itemId: 'item2', action: 'process' },
{ itemId: 'item3', action: 'process' },
];
await this.taskService.createStepFunctionTask({
input: items,
taskType: 'batch-processor',
tenantCode: 'tenant1',
}, { invokeContext });
ユースケース3:大規模CSVインポート
分散処理でCSVファイルから数百万行をインポートします。
シナリオ: バリデーションと変換を伴うS3からの大規模CSVファイルのインポート。
import { ProcessingMode } from '@mbc-cqrs-serverless/import';
// APIまたは直接呼び出しでCSVインポートをトリガー
await this.importService.createCsvImport({
s3Bucket: 'my-bucket',
s3Key: 'imports/data.csv',
tableName: 'products',
processingMode: ProcessingMode.STEP_FUNCTION,
});
// import-csvステートマシンが行うこと:
// 1. S3からCSVを読み込む
// 2. 行をバッチ化(デフォルト: 10行/バッチ)
// 3. 最大50バッチを並行処理
// 4. 各行を変換・バリデーション
// 5. インポートコマンドを作成
ユースケース4:非同期コールバックパターン
タスクトークンを使用して外部イベントを待機します。
シナリオ: ワークフローを続行する前に承認を待機します。
// ステートマシン定義で
{
"WaitForApproval": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke.waitForTaskToken",
"Parameters": {
"FunctionName": "${LambdaFunction}",
"Payload": {
"taskToken.$": "$$.Task.Token",
"requestId.$": "$.requestId"
}
},
"Next": "ProcessApproval"
}
}
// ハンドラーでタスクトークンを保存
async handleWaitForApproval(event: ApprovalEvent) {
await this.approvalService.createApprovalRequest({
requestId: event.input.requestId,
taskToken: event.taskToken, // 後でコールバックするために保存
});
}
// 承認を受け取ったらワークフローを再開
async approveRequest(requestId: string) {
const request = await this.approvalService.getRequest(requestId);
await this.sfnService.sendTaskSuccess({
taskToken: request.taskToken,
output: JSON.stringify({ approved: true }),
});
}
タスクトークンを使用したコールバックパターン
フレームワークは、長時間実行ワークフローの調整と外部イベントの待機のために、AWS Step Functionsタスクトークンを使用したコールバックパターンを実装しています。
コールバックパターンの仕組み
Step Functionの状態がWAIT_FOR_TASK_TOKEN統合パターンを使用すると、外部プロセスがタスクトークンとともに成功または失敗のレスポンスを送信するまで実行が一時停止します。
StepFunctionService実装
StepFunctionServiceは、実行の開始と一時停止したワークフローの再開のためのメソッドを提供します:
import { Injectable } from '@nestjs/common';
import {
SFNClient,
SendTaskSuccessCommand,
StartExecutionCommand,
} from '@aws-sdk/client-sfn';
@Injectable()
export class StepFunctionService {
private readonly client: SFNClient;
constructor(private readonly config: ConfigService) {
this.client = new SFNClient({
endpoint: config.get<string>('SFN_ENDPOINT'),
region: config.get<string>('SFN_REGION'),
});
}
// Start a new state machine execution (新しいステートマシン実行を開始)
startExecution(arn: string, input: any, name?: string) {
return this.client.send(
new StartExecutionCommand({
stateMachineArn: arn,
name: name && name.length <= 80 ? name : undefined,
input: JSON.stringify(input),
}),
);
}
// Resume a paused execution using task token (タスクトークンを使用して一時停止した実行を再開)
async resumeExecution(taskToken: string, output: any = {}) {
// Wrap output in the expected format for Lambda integration (Lambda統合の期待されるフォーマットで出力をラップ)
const wrappedOutput = {
Payload: [[output]],
};
return await this.client.send(
new SendTaskSuccessCommand({
taskToken: taskToken,
output: JSON.stringify(wrappedOutput),
}),
);
}
}
バージョンベースのコマンドチェーン
コマンドステートマシンは、コマンドがバージョン順に処理されることを保証するためにコールバックパターンを使用します:
// Wait for previous command to complete using task token (タスクトークンを使用して前のコマンドの完了を待機)
protected async waitConfirmToken(
event: DataSyncCommandSfnEvent,
): Promise<StepFunctionStateInput> {
// Store task token in DynamoDB for later callback (後のコールバックのためにタスクトークンをDynamoDBに保存)
await this.commandService.updateTaskToken(event.commandKey, event.taskToken);
return {
result: {
token: event.taskToken,
},
};
}
// When a command finishes, check if next version is waiting (コマンドが終了したら、次のバージョンが待機中かチェック)
protected async checkNextToken(
event: DataSyncCommandSfnEvent,
): Promise<StepFunctionStateInput> {
const nextCommand = await this.commandService.getNextCommand(
event.commandKey,
);
if (!nextCommand) {
return null; // No next command, chain ends (次のコマンドなし、チェーン終了)
}
if (nextCommand.taskToken) {
// Resume the waiting command (待機中のコマンドを再開)
try {
await this.sfnService.resumeExecution(nextCommand.taskToken, {
result: 'resumed_by_prev_version',
prevVersion: event.commandRecord.version,
});
} catch (e) {
this.logger.warn(
`Could not resume command v${nextCommand.version}: ${e.message}`,
);
}
}
return null;
}