すべての step.do コールバックは、第 1 引数として コンテキストオブジェクト(WorkflowStepContext)を受け取ります。コンテキストは、ステップ自身、現在のリトライ回数、そのステップで解決済みの設定について、ランタイム情報をステップのコードに渡します。
type WorkflowStepContext = {
step: {
name: string;
count: number;
};
attempt: number;
config: WorkflowStepConfig;
};| プロパティ | 型 | 説明 |
|---|---|---|
step.name |
string |
step.do に渡した名前です。 |
step.count |
number |
現在の Workflow 実行で、この名前の step.do がこれまで何回呼ばれたかです。ある名前での初回呼び出しは 1 から始まります。 |
attempt |
number |
現在の試行回数です(1 始まり)。最初の試行は 1、最初のリトライは 2、以降同様です。 |
config |
WorkflowStepConfig |
このステップで解決済みのリトライとタイムアウトの設定です。ランタイムが適用した既定値も含みます。 |
ステップ設定の retries.delay が関数の場合、動的な遅延は ctx.config.retries.delay には現れません。遅延関数は、現在のステップコンテキストと、リトライの原因になったエラーを含む、独自のコンテキストオブジェクトを受け取ります。
step.do のコールバックに引数を渡すと、コンテキストオブジェクトを受け取れます。
await step.do("my-step", async (ctx) => {
console.log(ctx.step.name); // "my-step"
console.log(ctx.step.count); // 1
console.log(ctx.attempt); // 1 on first try, 2 on first retry, etc.
console.log(ctx.config); // { retries: { limit: 5, ... }, timeout: "10 minutes" }
});独自の WorkflowStepConfig を渡す場合も、コンテキストを使えます。
await step.do(
"call an API",
{
retries: {
limit: 10,
delay: "10 seconds",
backoff: "exponential",
},
timeout: "30 minutes",
},
async (ctx) => {
console.log(ctx.config.retries.limit); // 10
console.log(ctx.config.timeout); // "30 minutes"
},
);遅延関数の設定は、動的なリトライ遅延を設定する を参照してください。
ctx.attempt を使い、リトライ時のステップの挙動を変えられます。たとえば、一定回数リトライしたあとにフォールバックのエンドポイントを使う、といったことができます。
await step.do(
"fetch data",
{ retries: { limit: 5, delay: "5 seconds", backoff: "linear" } },
async (ctx) => {
const url =
ctx.attempt <= 3
? "https://api.example.com/primary"
: "https://api.example.com/fallback";
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json();
},
);ctx.step を使い、ログに構造化メタデータを追加できます。
await step.do("process-order", async (ctx) => {
console.log(
JSON.stringify({
step: ctx.step.name,
stepCount: ctx.step.count,
attempt: ctx.attempt,
retryLimit: ctx.config.retries?.limit,
}),
);
// Your step logic here
});