跳到主要内容

用 WaitFor Timer 轮询

查看 Markdown

用 WaitFor Timer 轮询时,每一轮检查一次外部系统,每一轮都是一次新的 Step execution。当 Flow 等待云端构建、资源开通任务或第三方状态,并且想在 Flow 的历史中看到每一轮时,使用这个模式。

轮询 Step 在 WaitFor 中等待一个 Timer。它的 Execute 调用一次外部系统。工作还没完成时,Step 移动到自己,进入下一轮。

结构

轮询 Step 的每一轮执行以下步骤:

  1. WaitFor 返回一个轮询间隔的 Timer。
  2. Timer 触发后,Execute 调用一次外部 API,并给这次调用设置自己的短超时。
  3. 遇到临时错误时,Execute 返回这个错误。重试策略会再次运行这一轮。
  4. 遇到终态时,Execute 返回下一步的决定:成功或业务失败。
  5. 工作还没完成时,Execute 返回指向同一个 Step 的 GoTo,带上下一轮的输入。

“尚未就绪”是正常的决定。优先用它,而不是返回错误再靠重试循环。返回错误会把“尚未就绪”和真正的失败混在一起,还会消耗重试预算。

规则

  • 工作尚未就绪时,返回指向同一个 Step 的 GoTo。 每次 GoTo 都开始一次新的 Step execution,它会等待一个新的 Timer。
  • 给循环设上限。在 Step 输入里带上轮次编号,到达最大值就停止。 轮次上限限制的是检查次数,不是耗时:每一轮还要花时间在外部调用、重试和排队上。 需要硬性截止时间时,使用 Flow timeout(英文) 或 截止时间 watchdog。
  • Step 输入保持小而且大小固定,例如 job ID 和轮次编号。 累积的状态,例如收集到的结果,放在 Attribute 里,绝不放进不断变大的 Step 输入。
  • 在 Execute 中检查作业状态。不要在 WaitFor 中轮询外部系统。在这个模式中,WaitFor 只声明 Timer。
  • ExecuteRetry 使用少量带退避的尝试,处理临时错误。 重试用完后,用 ExecuteFailure 选项路由到一个短 Step,由它记录失败;见 Execute 失败恢复。
  • Timer 以整秒计时。间隔低于几秒时,使用 用长时间运行 Step 的 heartbeat 轮询。
  • 给 Timer 设一个 condition ID。测试里用 SkipTimer 跳过它, 不要缩短间隔;见 跳过 Timer。

示例

PollingWithTimerFlow 等待的模拟 job 与 heartbeat 示例 相同。StartJob 用 Flow ID 作为幂等的 job ID 启动 job。CheckJobStatus 等待一个 10 秒的 Timer,然后读取一次 job 状态。job 还在运行时,它带着下一个轮次编号移动到自己。60 轮之后它停止。重试用完时,它移动到 RecordJobWaitFailure,由后者用 recovery error 让 Flow 失败。

模拟 job 在启动六秒后成功,所以第一轮就会发现它已完成。调用 complete-job endpoint 可以提前完成它。

polling_with_timer_flow.pyPython
# MAX_POLL_ROUNDS bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
POLL_INTERVAL = timedelta(seconds=10)
POLL_INTERVAL_TIMER_ID = "poll-interval"
MAX_POLL_ROUNDS = 60
JOB_CALL_TIMEOUT = timedelta(seconds=10)


@dataclass(frozen=True)
class JobPollRound:
job_id: str
round_number: int


class CheckJobStatus(Step[JobPollRound]):
def __init__(self, jobs: FakeJobService) -> None:
self.jobs = jobs

def get_step_options(self) -> StepOptions:
return StepOptions(
execute_retry=RetryPolicy(
initial_interval=timedelta(seconds=1),
backoff_coefficient=2.0,
maximum_attempts=3,
),
).on_execute_failure_proceed_to(RecordJobWaitFailure)

def wait_for(self, context: Context, poll_round: JobPollRound) -> Wait:
return Wait.until(
Timer.by_duration(POLL_INTERVAL, condition_id=POLL_INTERVAL_TIMER_ID)
)

async def execute(
self, context: AsyncContext, poll_round: JobPollRound
) -> StepDecision:
status = await asyncio.wait_for(
self.jobs.get_job_status(poll_round.job_id),
JOB_CALL_TIMEOUT.total_seconds(),
)
if status.state is JobState.SUCCEEDED:
return graceful_complete(status.result)
if status.state is JobState.FAILED:
return force_fail(f"job {poll_round.job_id} failed")
if poll_round.round_number >= MAX_POLL_ROUNDS:
return force_fail(
f"job {poll_round.job_id} did not finish in {MAX_POLL_ROUNDS} rounds"
)
next_round = JobPollRound(poll_round.job_id, poll_round.round_number + 1)
return go_to(CheckJobStatus, next_round)

例子: examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py

比较两种轮询模式

用 WaitFor Timer 轮询会把每一轮都记录在 Flow 的历史中。你能清楚看到每一轮,也能用 Time Travel 回到某一轮。它稍微重一些。

用长时间运行 Step 的 heartbeat 轮询 更轻量。一次 Step execution 承担整个等待。

行为WaitFor Timer长时间运行 Step 的 heartbeat
每一轮Flow 历史中一次新的 Step execution一次尝试内的一次 heartbeat 或一条 Stream message
两轮之间不占用 Worker task slot这次尝试一直占用一个 Worker task slot
Dex Server failoverTimer 等待继续,不消耗重试;Worker 已收到的 WaitFor 或 Execute 尝试会失败,并消耗一次重试正在运行的尝试失败,并消耗一次重试
间隔整秒任意间隔

准确的 failover 规则,包括 ASYNC 的例外,见 Lease(英文)。

间隔长、要看到每一轮、或者要用 Time Travel 回到某一轮时,选这个模式。间隔短、或者要最轻量的循环时,选 heartbeat 模式。Time Travel 只能回到运行近期历史窗口内的轮次;见 用 Time Travel 恢复 Flow。

下一步