Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Workers API

最終更新 Markdown で表示Agent セットアップ

このガイドは、Cloudflare Workers 内の Workflows API のメソッド、型、使用例を詳しく説明します。

WorkflowEntrypoint

WorkflowEntrypoint クラスは、Workflow 定義の中核です。Workflow はこのクラスを拡張し、有効な Workflow と見なされるには少なくとも 1 つの step 呼び出しを持つ run メソッドを定義する必要があります。

export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
	async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
		// Steps here
	}
}

run

  • run(event: WorkflowEvent<T>, step: WorkflowStep): Promise<T>
    • event - Workflow に渡されるイベント。データを含む任意の payload(パラメーター)を含みます
    • step - Workflow の step メソッドを提供する WorkflowStep

run メソッドは任意でデータを返せます。返したデータは、Workers APIREST API、Workflows ダッシュボードでインスタンスの状態を照会するときに利用できます。Workflow が結果を計算する、オブジェクトストレージに保存したデータのキーを返す、操作が必要な識別子を生成する、といった場合に役立ちます。

export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
	async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
		// Steps here
		let someComputedState = await step.do("my step", async () => {});

		// Optional: return state from our run() method
		return someComputedState;
	}
}

WorkflowEvent 型は任意の 型パラメーター を受け付け、WorkflowEvent 内の payload プロパティの型を指定できます。

Workflow コード内でのイベントの扱いは、イベントとパラメーター のドキュメントを参照してください。

最後に、任意の JS 制御フロープリミティブ(if 条件、ループ、try...catch ブロック、promise など)を使い、run メソッド内のステップを管理できます。

WorkflowEvent

export type WorkflowCronSchedule = {
	/** Cron expression that triggered this event. */
	cron: string;
	/** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */
	scheduledTime: number;
};

export type WorkflowEvent<T> = {
	payload: Readonly<T>;
	timestamp: Date;
	instanceId: string;
	workflowName: string;
	schedule?: WorkflowCronSchedule;
};
  • WorkflowEvent は、Workflow の run メソッドの最初の引数です。
    • payload - デフォルト型は any。型パラメーターが提供された場合は型 T
    • timestamp - Workflow インスタンスが作成(トリガー)された時刻に設定された Date オブジェクト。
    • instanceId - 関連インスタンスの ID。
    • workflowName - 関連 Workflow の名前。
    • schedule - cron スケジュールで作成された Workflow インスタンスのメタデータ。cron 式と Unix エポックからのミリ秒である scheduledTime を含みます。

Workflow コード内でのイベントの扱いは、イベントとパラメーター のドキュメントを参照してください。

WorkflowStep

step

  • step.do(name: string, callback: (ctx: WorkflowStepContext): RpcSerializable): Promise<T>
  • step.do(name: string, callback: (ctx: WorkflowStepContext): RpcSerializable, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>
  • step.do(name: string, config?: WorkflowStepConfig, callback: (ctx: WorkflowStepContext): RpcSerializable): Promise<T>
    • name - ステップの名前。最大 256 文字。
    • config(任意) - ステップ固有のリトライ動作 を構成する任意の WorkflowStepConfig
    • callback - WorkflowStepContext を受け取り、Workflow が永続化するシリアライズ可能な状態を任意で返す非同期関数。JavaScript Workflows では、大きなバイナリ出力向けに、新しくロックされていない ReadableStream<Uint8Array> も含みます。
  • step.do(name: string, config?: WorkflowStepConfig, callback: (ctx: WorkflowStepContext): RpcSerializable, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>
    • name - ステップの名前。最大 256 文字。
    • config(任意) - ステップ固有のリトライ動作 を構成する任意の WorkflowStepConfig
    • callback - WorkflowStepContext を受け取り、Workflow が永続化するシリアライズ可能な状態を任意で返す非同期関数。JavaScript Workflows では、大きなバイナリ出力向けに、新しくロックされていない ReadableStream<Uint8Array> も含みます。
    • rollbackOptions(任意) - ステップのロールバックロジックを登録します。Workflow が後で失敗した場合、登録済みロールバックはステップ開始の逆順で実行されます。

ReadableStream<Uint8Array> オブジェクトがステップ内で永続化されたあと、再利用しないでください。step から返される新しいストリームを使います。バイトは元のストリームから保存されますが、実装は異なることがあります。

:::

export class MyWorkflow extends WorkflowEntrypoint {
	async run(_event, step) {
		const reportStream = await step.do("read report from R2", async () => {
			const object = await this.env.MY_BUCKET.get("reports/latest.csv");

			if (!object?.body) {
				throw new Error("Could not read reports/latest.csv from R2.");
			}

			return object.body;
		});

		const preview = await new Response(reportStream).text();
		return { preview };
	}
}
type Env = {
	MY_BUCKET: R2Bucket;
};

export class MyWorkflow extends WorkflowEntrypoint<Env> {
	async run(_event: WorkflowEvent<unknown>, step: WorkflowStep) {
		const reportStream = await step.do("read report from R2", async () => {
			const object = await this.env.MY_BUCKET.get("reports/latest.csv");

			if (!object?.body) {
				throw new Error("Could not read reports/latest.csv from R2.");
			}

			return object.body;
		});

		const preview = await new Response(reportStream).text();
		return { preview };
	}
}
  • step.sleep(name: string, duration: WorkflowDuration): Promise<void>
    • name - ステップの名前。
    • duration - スリープする期間。ミリ秒の number、または WorkflowDuration 互換の文字列。
    • Workflow のリトライの詳細は スリープとリトライのドキュメント を参照してください。
  • step.sleepUntil(name: string, timestamp: Date | number): Promise<void>
    • name - ステップの名前。
    • timestamp - Workflow インスタンスをスリープさせる先の、JavaScript Date オブジェクトまたは Unix エポックからのミリ秒。
  • step.waitForEvent(name: string, options: ): Promise<void>- name - ステップの名前。 - options - type(最大 100 文字 1)のプロパティを持つオブジェクト。この waitForEvent 呼び出しが instance.sendEvent 呼び出し時にどのイベントタイプと一致するかを決めます。任意の timeout プロパティは、タイムアウト例外をスローする前に waitForEvent 呼び出しがブロックする時間を定義します。デフォルトのタイムアウトは 24 時間です。
export class MyWorkflow extends WorkflowEntrypoint {
	async run(event, step) {
		// Other steps in your Workflow
		let stripeEvent = await step.waitForEvent(
			"receive invoice paid webhook from Stripe",
			{ type: "stripe-webhook", timeout: "1 hour" },
		);
		// Rest of your Workflow
	}
}
export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
	async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
		// Other steps in your Workflow
		let stripeEvent = await step.waitForEvent<IncomingStripeWebhook>(
			"receive invoice paid webhook from Stripe",
			{ type: "stripe-webhook", timeout: "1 hour" },
		);
		// Rest of your Workflow
	}
}

実行中の Workflow インスタンスへイベントを送る方法は、イベントとパラメーター のドキュメントを確認してください。

WorkflowStepConfig

export type WorkflowDynamicDelayContext = {
	ctx: WorkflowStepContext;
	error: Error;
};

export type WorkflowDelayFunction = (
	input: WorkflowDynamicDelayContext,
) => string | number | Promise<string | number>;

export type WorkflowStepConfig = {
	retries?: {
		limit: number;
		delay: string | number | WorkflowDelayFunction;
		backoff?: WorkflowBackoff;
	};
	timeout?: string | number;
};
  • WorkflowStepConfig は、WorkflowStepdo メソッドへの任意の引数です。そのステップのリトライ動作を構成できるプロパティを定義します。
  • retries.delay を固定期間に設定するか、現在のステップコンテキストとスローされたエラーから次のリトライ遅延を計算する WorkflowDelayFunction を渡します。

Workflow のリトライの詳細は スリープとリトライのドキュメント を参照してください。

ロールバックオプション

type WorkflowRollbackContext<T = unknown> = {
	ctx: WorkflowStepContext;
	error: Error;
	output: T | undefined;
};

type WorkflowRollbackHandler<T = unknown> = (
	ctx: WorkflowRollbackContext<T>,
) => Promise<void>;

type WorkflowStepRollbackConfig = Pick<
	WorkflowStepConfig,
	"retries" | "timeout"
>;

type WorkflowStepRollbackOptions<T = unknown> = {
	rollback: WorkflowRollbackHandler<T>;
	rollbackConfig?: WorkflowStepRollbackConfig;
};
  • この WorkflowStepRollbackOptions オブジェクトを step.do() の最後の引数として渡し、成功したステップの補償アクションを登録します。
  • rollback は、元のステップコンテキスト、Workflow 失敗の原因となったエラー、フォワードステップが返したステップ出力を受け取ります。
  • rollbackConfig は、ロールバックハンドラー自体にリトライとタイムアウト設定を適用します。
export class BillingWorkflow extends WorkflowEntrypoint {
	async run(_event, step) {
		await step.do(
			"create charge",
			async () => {
				const charge = await createCharge();
				return { chargeId: charge.id };
			},
			{
				rollback: async ({ ctx, output, error }) => {
					const { chargeId } = output;
					await refundCharge(chargeId, {
						reason: `${ctx.step.name}: ${error.message}`,
					});
				},
				rollbackConfig: {
					retries: {
						limit: 3,
						delay: "30 seconds",
						backoff: "linear",
					},
					timeout: "5 minutes",
				},
			},
		);
	}
}
export class BillingWorkflow extends WorkflowEntrypoint<Env> {
	async run(_event: WorkflowEvent<unknown>, step: WorkflowStep) {
		await step.do(
			"create charge",
			async () => {
				const charge = await createCharge();
				return { chargeId: charge.id };
			},
			{
				rollback: async ({ ctx, output, error }) => {
					const { chargeId } = output as { chargeId: string };
					await refundCharge(chargeId, {
						reason: `${ctx.step.name}: ${error.message}`,
					});
				},
				rollbackConfig: {
					retries: {
						limit: 3,
						delay: "30 seconds",
						backoff: "linear",
					},
					timeout: "5 minutes",
				},
			},
		);
	}
}

WorkflowStepContext

export type WorkflowStepContext = {
	step: {
		name: string;
		count: number;
	};
	attempt: number;
	config: WorkflowStepConfig;
};
  • WorkflowStepContext は、step.do コールバック関数の最初の引数として渡されます。現在のステップに関するランタイム情報を提供します。
    • step.name - step.do に渡されたステップの名前。
    • step.count - 現在の Workflow 実行で、この名前で step.do が呼び出された回数(1 始まり)。
    • attempt - 現在の試行番号(1 始まり)。最初の試行は 1、最初のリトライは 2、という具合です。
    • config - このステップの解決済み WorkflowStepConfig。ランタイムが適用したデフォルトを含みます。

使用例は ステップコンテキストのドキュメント を参照してください。

Workflow のステップ上限

Workers Paid 上の各 Workflow は、デフォルトで 10,000 ステップに対応します。Wrangler 構成の Workflow 定義の limits プロパティ内で steps を構成すると、最大 25,000 ステップまで増やせます。

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "workflows": [
    {
      "name": "my-workflow",
      "binding": "MY_WORKFLOW",
      "class_name": "MyWorkflow",
      "limits": {
        "steps": 25000
      }
    }
  ]
}
[[workflows]]
name = "my-workflow"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"

[workflows.limits]
steps = 25_000

step.sleep は最大ステップ上限には数えられません。

Workers Free 上の Workflows の上限は 1,024 ステップです。詳細は Workflow の上限 を参照してください。

NonRetryableError

  • throw new NonRetryableError(message: string, name string optional): NonRetryableError
    • step.do() 内でスローすると、このエラーはステップのリトライを止め、エラーをトップレベル(run 関数)へ伝播します。このトップレベルで処理されないエラーは、Workflow インスタンスを失敗させます。
    • Workflows ステップのリトライの詳細は スリープとリトライのドキュメント を参照してください。

Workers から Workflows を呼び出す

Workflows は、バインディング の概念経由で、Workers スクリプトへ直接 API を公開します。バインディングを使うと、API キーやクライアントを管理せずに Workflow を安全に呼び出せます。

Wrangler 構成内で [[workflows]] バインディングを定義し、Workflow にバインドできます。

たとえば、workflows-starter という Workflow にバインドし、Worker スクリプトの MY_WORKFLOW 変数で使えるようにするには、[[workflows]] バインディング定義内で次のフィールドを構成します。

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "workflows-starter",
	"main": "src/index.ts",
	// Set this to today's date
	"compatibility_date": "2026-09-20",
	"workflows": [
		{
			// name of your workflow
			"name": "workflows-starter",
			// binding name env.MY_WORKFLOW
			"binding": "MY_WORKFLOW",
			// this is class that extends the Workflow class in src/index.ts
			"class_name": "MyWorkflow",
		},
	],
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "workflows-starter"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-09-20"

[[workflows]]
name = "workflows-starter"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"

Pages からバインドする

Workflow 定義を持つ Workers プロジェクトをデプロイし、サービスバインディング または標準の fetch() 呼び出しでその Worker を呼び出すことで、Pages Functions から Workflows をバインドしてトリガーできます。

例は Pages から Workflows を呼び出す のドキュメントを参照してください。

クロススクリプト呼び出し

Workflow 定義がある Worker スクリプトとは別の Worker スクリプトから、Workflow にバインドすることもできます。そのためには、Wrangler 構成の [[workflows]] バインディング定義に、スクリプト名を script_name キーで指定します。

たとえば、Workflow が billing-worker という Worker スクリプトで定義され、web-api-worker スクリプトから呼び出す場合、Wrangler 構成ファイル は次のようになります。

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "web-api-worker",
	"main": "src/index.ts",
	// Set this to today's date
	"compatibility_date": "2026-09-20",
	"workflows": [
		{
			// name of your workflow
			"name": "billing-workflow",
			// binding name env.MY_WORKFLOW
			"binding": "MY_WORKFLOW",
			// this is class that extends the Workflow class in src/index.ts
			"class_name": "MyWorkflow",
			// the script name where the Workflow is defined.
			// required if the Workflow is defined in another script.
			"script_name": "billing-worker",
		},
	],
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "web-api-worker"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-09-20"

[[workflows]]
name = "billing-workflow"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"
script_name = "billing-worker"

TypeScript を使う場合は、Wrangler 設定ファイルを変更するたびに wrangler types を実行します。バインディングに基づく env オブジェクトの型と、ランタイム型 が生成されます。

Workflow

Workflow 型は、Worker スクリプト内から実行中の Workflow インスタンスを作成、状態を検査、管理できるメソッドを提供します。 wrangler types が生成する型の一部です。

./worker-configuration.d.tsts
interface Env {
	// The 'MY_WORKFLOW' variable should match the "binding" value set in the Wrangler config file
	MY_WORKFLOW: Workflow;
}

Workflow 型は次のメソッドをエクスポートします。

create

指定した Workflow の新しいインスタンスを作成(トリガー)します。

  • create(options?: WorkflowInstanceCreateOptions): Promise<WorkflowInstance>
    • options - インスタンス作成時に渡す任意のプロパティ。ユーザー指定の ID とペイロードパラメーターを含みます。

ID は自動生成されますが、ユーザー指定の ID(最大 100 文字 1)も指定できます。Workflows をユーザー、加盟店、その他のシステム内識別子に対応付けるときに役立ちます。params プロパティとして JSON オブジェクトを渡し、Workflow インスタンスが WorkflowEvent として処理するデータを渡せます。

// Create a new Workflow instance with your own ID and pass params to the Workflow instance
let instance = await env.MY_WORKFLOW.create({
	id: myIdDefinedFromOtherSystem,
	params: { hello: "world" },
});
return Response.json({
	id: instance.id,
	details: await instance.status(),
});

WorkflowInstance を返します。

提供した ID が、まだ 保持上限 を過ぎていない既存インスタンスで使われている場合はエラーをスローします。同じ ID でワークフローを再実行するには、既存インスタンスを restart できます。

Workers APIcreate メソッドで Workflow インスタンスを作成(トリガー)するときにも、Workflows 型に型パラメーターを渡せます。ただし、型情報は Workflow 本体には伝播しません。TypeScript の型はビルド時の構成だからです。

Workflow に任意の型パラメーターを提供するには、Workflow バインディングを定義するときに型引数を渡します。

interface User {
	email: string;
	createdTimestamp: number;
}

interface Env {
	// Pass our User type as the type parameter to the Workflow definition
  MY_WORKFLOW: Workflow<User>;
}

export default {
	async fetch(request, env, ctx) {
		// More likely to come from your database or via the request body!
		const user: User = {
			email: [email protected],
			createdTimestamp: Date.now()
		}

		let instance = await env.MY_WORKFLOW.create({
			// params expects the type User
			params: user
		})

		return Response.json({
			id: instance.id,
			details: await instance.status(),
		});
	}
}

createBatch

指定した Workflow の新しいインスタンスを、一度に最大 100 件までバッチ作成(トリガー)します。

複数インスタンスを一度にスケジュールするときに役立ちます。createBatch の呼び出しは、(単一インスタンスの)create の呼び出しと同じ扱いであり、インスタンス作成上限 の範囲で作業できます。

  • createBatch(batch: WorkflowInstanceCreateOptions[]): Promise<WorkflowInstance[]>
    • batch - インスタンス作成時に渡す Options のリスト。ユーザー指定の ID とペイロードパラメーターを含みます。

batch リストの各要素は、idparams の両方のプロパティを含むことが期待されます。

// Create a new batch of 3 Workflow instances, each with its own ID and pass params to the Workflow instances
const listOfInstances = [
	{ id: "id-abc123", params: { hello: "world-0" } },
	{ id: "id-def456", params: { hello: "world-1" } },
	{ id: "id-ghi789", params: { hello: "world-2" } },
];
let instances = await env.MY_WORKFLOW.createBatch(listOfInstances);

WorkflowInstance の配列を返します。

create と違い、この操作はべき等で、ID がすでに使われていても失敗しません。同じ ID の既存インスタンスがまだ 保持上限 内にある場合はスキップされ、返される配列から除外されます。

deleteBatch

最大 100 件の Workflow インスタンスとその保存済み状態を削除します。

deleteBatch(instanceIds: string[])Promise<WorkflowBatchDeleteResult> を返します。instanceIds 引数には、削除する Workflow インスタンスの ID が含まれます。

const result = await env.MY_WORKFLOW.deleteBatch([
	"instance-abc",
	"instance-def",
]);
const result = await env.MY_WORKFLOW.deleteBatch([
	"instance-abc",
	"instance-def",
]);

操作は成功と、インスタンス単位の失敗を返します。

type WorkflowBatchDeleteResult = {
	deleted: { id: string }[];
	errors: {
		id: string;
		code: number;
		message: string;
	}[];
};

deleted には正常に削除された ID が含まれます。errors には、インスタンス ID で識別される失敗が、安定したエラーコードとメッセージとともに含まれます。

deleteBatch() は 1 から 100 個の ID を受け付けます。重複 ID は上限に数えられ、1 回削除されます。結果は各入力位置に繰り返されます。インスタンスが存在しない ID は errors に含まれます。いずれかの ID が無効な場合、インスタンスを削除する前に呼び出しは失敗します。実行中のインスタンスを削除すると、保存済み状態が削除され、ロールバックハンドラーを実行せずに現在の実行が停止します。

get

ID で特定の Workflow インスタンスを取得します。

  • get(id: string): Promise<WorkflowInstance>- id - Workflow インスタンスの ID。

WorkflowInstance を返します。インスタンス ID が存在しない場合は例外をスローします。

// Fetch an existing Workflow instance by ID:
try {
	let instance = await env.MY_WORKFLOW.get(id);
	return Response.json({
		id: instance.id,
		details: await instance.status(),
	});
} catch (e: any) {
	// Handle errors
	// .get will throw an exception if the ID doesn't exist or is invalid.
	const msg = `failed to get instance ${id}: ${e.message}`;
	console.error(msg);
	return Response.json({ error: msg }, { status: 400 });
}

WorkflowInstanceCreateOptions

インスタンス作成時に渡す任意のプロパティです。

interface WorkflowInstanceCreateOptions {
	/**
	 * An id for your Workflow instance. Must be unique within the Workflow.
	 */
	id?: string;
	/**
	 * The event payload the Workflow instance is triggered with
	 */
	params?: unknown;
	/**
	 * The retention policy for the Workflow instance.
	 * Defaults to the maximum retention period available for the owner's account.
	 */
	retention?: {
		/**
		 * How long to retain instance state after the Workflow completes successfully.
		 */
		successRetention?: WorkflowRetentionDuration;
		/**
		 * How long to retain instance state after the Workflow ends in an errored or terminated state.
		 */
		errorRetention?: WorkflowRetentionDuration;
	};
}

type WorkflowRetentionDuration = WorkflowSleepDuration;

retention が設定されていない場合、インスタンス状態はアカウントで利用できる最大保持期間(Workers Free プランでは 3 日、Workers Paid プランでは 30 日)保持されます。詳細は 保持上限 を参照してください。

次の例は、成功後は 1 日、エラー後は 7 日状態を保持するインスタンスを作成します。

let instance = await env.MY_WORKFLOW.create({
	id: myIdDefinedFromOtherSystem,
	params: { hello: "world" },
	retention: {
		successRetention: "1 day",
		errorRetention: "7 days",
	},
});

WorkflowInstance

特定の Workflow インスタンスを表し、インスタンスを管理するメソッドを提供します。

declare abstract class WorkflowInstance {
	public id: string;
	/**
	 * Pause the instance.
	 */
	public pause(): Promise<void>;
	/**
	 * Resume the instance. If it is already running, an error will be thrown.
	 */
	public resume(): Promise<void>;
	/**
	 * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.
	 */
	public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;
	/**
	 * Restart the instance from the beginning, or from a specific step.
	 */
	public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;
	/**
	 * Delete the instance and its stored state.
	 */
	public delete(): Promise<void>;
	/**
	 * Returns the current status of the instance.
	 */
	public status(): Promise<InstanceStatus>;
	/**
	 * Subscribe to events from this Workflow instance.
	 */
	public subscribe(
		options?: WorkflowInstanceSubscribeOptions,
	): Promise<WorkflowInstanceSubscription>;
}

id

Workflow の id を返します。

  • id: string

status

実行中の Workflow インスタンスの状態を返します。

  • status(): Promise<InstanceStatus>

pause

実行中の Workflow インスタンスを一時停止します。

  • pause(): Promise<void>

resume

一時停止した Workflow インスタンスを再開します。

  • resume(): Promise<void>

restart

Workflow インスタンスを先頭から、または特定のステップから再起動します。

  • restart(options?: WorkflowInstanceRestartOptions): Promise<void>
    • options - インスタンスの再起動位置を制御する任意のプロパティ。
let instance = await env.MY_WORKFLOW.get("abc-123");

// Restart the instance from the beginning.
await instance.restart();

// Restart the instance from the step named "aggregate".
await instance.restart({ from: { name: "aggregate" } });

// Restart the instance from the third call to a step named "process".
await instance.restart({ from: { name: "process", count: 3 } });

特定のステップから再起動する場合、それより前のすべてのステップのキャッシュ結果は再利用され、対象ステップとその後のステップは再実行されます。インスタンスの実行履歴に from に一致するステップがない場合、呼び出しはエラーをスローします。

WorkflowInstanceRestartOptions

interface WorkflowInstanceRestartOptions {
	/**
	 * The step to restart the instance from.
	 * If omitted, the instance restarts from the beginning.
	 */
	from?: {
		/**
		 * The name of the step.
		 */
		name: string;
		/**
		 * The 1-based index of the step, used when multiple steps share the same name and type. Defaults to 1 (the first occurrence).
		 */
		count?: number;
		/**
		 * The step type. Use this to disambiguate when the same name is shared across step types. Defaults to "do".
		 */
		type?: "do" | "sleep" | "waitForEvent";
	};
}

from オブジェクトは、再起動元のステップを識別します。必須なのは name だけです。同じステップ名が実行内で複数回現れる場合にのみ、counttype が必要です。

  • name - ステップの名前。
  • count - ステップの 1 始まりのインデックス。複数ステップが同じ名前とタイプを共有する場合に使います(例: ループ内)。デフォルトは 1(最初の出現)です。ステップコンテキストstep.count に対応します。
  • type - ステップタイプ("do""sleep"、または "waitForEvent")。デフォルトは "do" です。異なるステップタイプで同じ名前が共有されるときに使います。

terminate

Workflow インスタンスを終了します。

  • terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>
    • options - インスタンスの終了方法を制御する任意のプロパティ。
let instance = await env.MY_WORKFLOW.get("abc-123");

// Terminate without running rollback handlers.
await instance.terminate();

// Run registered rollback handlers before terminating.
await instance.terminate({ rollback: true });

rollbacktrue の場合、インスタンスが terminated 状態に達する前に、完了済みまたは対象となるステップが登録したロールバックハンドラーを Workflows が実行します。ロールバックハンドラーのないステップはスキップされます。

WorkflowInstanceTerminateOptions

interface WorkflowInstanceTerminateOptions {
	/**
	 * If true, run registered rollback handlers before terminating the instance.
	 */
	rollback?: boolean;
}

delete

delete(): Promise<void> で Workflow インスタンスとその保存済み状態を削除します。

const instance = await env.MY_WORKFLOW.get("instance-abc");
await instance.delete();
const instance = await env.MY_WORKFLOW.get("instance-abc");
await instance.delete();

実行中のインスタンスを削除すると、ロールバックハンドラーを実行せずに現在の実行が停止します。Workflow が自身のインスタンスを削除する場合、実行は await instance.delete() の間に停止し、呼び出し後のコードは実行されません。

sendEvent

実行中の Workflow インスタンスへ イベントを送ります

  • sendEvent(): Promise<void>- options - Workflow インスタンスへ送るイベント type (最大 100 文字 1)と payloadtype は、Workflow 内の対応する waitForEvent 呼び出しの type と一致する必要があります。

成功時は void を返します。Workflow が実行中でない、またはエラー状態の場合は例外をスローします。

export default {
	async fetch(req, env) {
		const instanceId = new URL(req.url).searchParams.get("instanceId");
		const webhookPayload = await req.json();

		let instance = await env.MY_WORKFLOW.get(instanceId);
		// Send our event, with `type` matching the event type defined in
		// our step.waitForEvent call
		await instance.sendEvent({
			type: "stripe-webhook",
			payload: webhookPayload,
		});

		return Response.json({
			status: await instance.status(),
		});
	},
};
export default {
	async fetch(req: Request, env: Env) {
		const instanceId = new URL(req.url).searchParams.get("instanceId");
		const webhookPayload = await req.json<Payload>();

		let instance = await env.MY_WORKFLOW.get(instanceId);
		// Send our event, with `type` matching the event type defined in
		// our step.waitForEvent call
		await instance.sendEvent({
			type: "stripe-webhook",
			payload: webhookPayload,
		});

		return Response.json({
			status: await instance.status(),
		});
	},
};

sendEvent は複数回呼び出せます。type プロパティの値を、Workflow 内の特定の waitForEvent 呼び出しに一致させます。

これにより、複数のイベントを一度に待つか、Promise.race を使って複数イベントを待ち、最初のイベントで Workflow を進められます。

subscribe

Workflow インスタンスからの過去およびライブの実行イベントを購読します。

  • subscribe(options?: WorkflowInstanceSubscribeOptions): Promise<WorkflowInstanceSubscription>
    • options - 開始カーソルとフィルタするイベントタイプを設定する任意のプロパティ。

返される購読は next() メソッドを提供します。各呼び出しは、次に一致する WorkflowInstanceEvent を返すか、それを待ちます。インスタンスが完了、エラー、または終了すると購読は終わります。

WorkflowInstanceSubscribeOptions

interface WorkflowInstanceSubscribeOptions {
	/**
	 * The event ID after which to start.
	 */
	cursor?: number;
	/**
	 * Emit only events with one of these types.
	 */
	filter?: WorkflowInstanceEventType[];
}

type WorkflowInstanceEventType = WorkflowInstanceEvent["type"];

オプションなしで subscribe() を呼び出すと、すべてのイベントを受け取ります。cursorfilter を使い、購読が返すイベントを制御します。

const instance = await env.MY_WORKFLOW.get("abc-123");

// Subscribe to all events.
using allEvents = await instance.subscribe();

// Subscribe to events after event ID 100.
using eventsAfterCursor = await instance.subscribe({ cursor: 100 });

// Subscribe to selected event types.
using filteredEvents = await instance.subscribe({
	filter: ["workflow_completed", "workflow_errored"],
});
const instance = await env.MY_WORKFLOW.get("abc-123");

// Subscribe to all events.
using allEvents = await instance.subscribe();

// Subscribe to events after event ID 100.
using eventsAfterCursor = await instance.subscribe({ cursor: 100 });

// Subscribe to selected event types.
using filteredEvents = await instance.subscribe({
	filter: ["workflow_completed", "workflow_errored"],
});

イベントタイプ、フィルタ動作、カーソルの使い方は イベントを購読する を参照してください。

InstanceStatus

Workflow インスタンスの状態の詳細です。

type InstanceStatus = {
	status:
		| "queued" // means that instance is waiting to be started (see concurrency limits)
		| "running"
		| "paused"
		| "errored"
		| "terminated" // user terminated the instance while it was running
		| "complete"
		| "waiting" // instance is hibernating and waiting for sleep or event to finish
		| "waitingForPause" // instance is finishing the current work to pause
		| "unknown";
	error?: {
		name: string;
		message: string;
	};
	output?: unknown;
	rollback: {
		outcome: "complete" | "failed";
		error: {
			name: string;
			message: string;
		} | null;
	} | null;
};

Workflow がロールバックに入ると、Workers API は互換性のため、ロールバック実行中も status: "running" を報告し続けます。インスタンスが終端状態に達したあと、rollback を検査し、補償ステップが正常に完了したか失敗したかを判断します。

Footnotes

  1. 一致パターン: ^[a-zA-Z0-9_][a-zA-Z0-9-_]*$ 2 3

役に立ちましたか?