用长时间运行 Step 的 heartbeat 轮询
查看 Markdown用长时间运行 Step 的 heartbeat 轮询,在一次 Step execution 里等待外部系统。当 Flow 等待云端构建、Kubernetes rollout、资源开通任务或第三方 API 的状态,并且想要最轻量的轮询循环时,使用这个模式。
整个等待由一个 Step 负责。它的 Execute 调用外部 API,sleep,然后再次调用,直到工作进入终态。用 WaitFor Timer 轮询 等待同类系统时,每一轮是一次 Step execution。
Dex 内部的业务信号,例如 Channel message 和 RPC,不属于 polling。用 WaitFor 等待它们。TTL、提醒、不活跃截止时间等业务 Timer 也使用 WaitFor;见 持久化定时器。
结构
轮询 Step 重复以下步骤:
- 调用外部 API,并给这次调用设置自己的短超时,例如 10 秒。
- 遇到临时错误时,返回这个错误。重试策略会再次运行这个 Step。
- 遇到终态时,返回下一步的决定:成功或业务失败。
- 报告进度。状态变化时写一条 Stream 消息,否则带着 checkpoint 记录一次 heartbeat。
- 按轮询间隔 sleep,然后重新开始。
“尚未就绪”是循环里的正常分支。优先用它,而不是返回错误再靠重试循环。返回错误会把“尚未就绪”和真正的失败混在一起,还会消耗重试预算。
普通的 sleep 就够了。通过该语言 SDK 的机制响应取消。外部调用支持取消参数时,把它传进去。观察不到取消的阻塞调用要有自己的 timeout,因为 handler 返回之后 Worker 槽才会释放。取消是协作式的:循环在下一个能报告取消的边界退出。见 Make the Step stop(英文)。
规则
- 每一轮都要落在 heartbeat 窗口内;计算方法见 Heartbeat(英文)。用户正在等待时,间隔用几秒;构建这类长任务,用几十秒。
ExecuteMethodTimeout和TotalDuration使用同一个最长等待时间。Dex 会强制执行这两个值,所以 Step 不需要自己计算截止时间。失败之后,TotalDuration只决定是否安排下一次尝试。排队可能让已安排的尝试晚开始,进行中的尝试也不会被截断,所以整个等待可能比它晚很多才结束。Flow 的业务截止时间用下面的 watchdog。ExecuteRetry使用少量带退避的尝试,用于处理临时错误和 Worker 崩溃。见 Timeouts 和 total duration(英文)。Polling Step 可以使用任一种 durability。- 等待超时后,Step 失败。用
ExecuteFailure选项把这个失败路由到一个短 Step,由它记录业务失败;见 Execute 失败恢复。失败记录不包含最后的状态;从 Stream 或日志中读取它。 - 其他业务条件仍然在循环中检查,例如由其他系统持有、可能过期的 lease。这些 timeout 只能限定固定时长。
- 业务截止时间比整个等待短,或者轮询 Step 为了提交每次状态变化而重新进入自身、Step options 无法守住截止时间时,使用 watchdog。watchdog 是一个与自己的 Timer 竞争的等待 Step。它和记录结果的 Step 声明同一个 Attribute lock。Timer 触发时,它在这个 lock 下读取状态,只有工作仍未完成时才判定超期。
- 从上一个 checkpoint 继续,用
GetLastHeartbeatValue读取它。示例中的 checkpoint 是上一次报告的 job 状态。从最后存储的 checkpoint 继续,可以减少重试后重复发送的进度消息。checkpoint 可能丢失,所以消费方必须容忍重复和缺失的消息;见 Heartbeat(英文)。 - 只在观察到的状态变化时写入一条 Stream message,其余轮次记录 heartbeat。Stream message 是 best-effort,所以消费方从持久化状态恢复,例如 Attribute、读取 RPC 或 Flow 结果。
- 由 polling Step 返回结果,需要加锁提交的内容放到随后一个短 Step 中。如果 polling Step 在整个等待期间持有 lock,需要它的 Step(例如 watchdog)都要等到循环结束,需要它的 RPC 都会失败。
示例
PollingFlow 等待一个模拟的外部 job。StartJob 以 Flow ID 作为幂等 job ID 启动 job。AwaitJob 每两秒查询一次 job 状态。状态变化时写入一条 JobProgress Stream message,并以 job 结果完成。每次尝试最多持续十分钟。失败之后,十分钟的重试预算决定是否开始下一次尝试。Dex 不再开始新的尝试时,AwaitJob 移动到 RecordJobWaitFailure。这个 Step 以恢复错误让 Flow 失败。
模拟 job 先报告 QUEUED,然后是 RUNNING,启动六秒后成功。调用 complete-job endpoint 可以让它提前完成。
# Keep POLL_INTERVAL + JOB_CALL_TIMEOUT <= heartbeat_timeout - 10s.
# MAX_JOB_WAIT bounds each attempt and whether another attempt starts; Dex enforces it.
POLL_INTERVAL = timedelta(seconds=2)
JOB_CALL_TIMEOUT = timedelta(seconds=10)
MAX_JOB_WAIT = timedelta(minutes=10)
JOB_PROGRESS = Stream("JobProgress", JobStatus, 1 << 20)
class RecordJobWaitFailure(Step[str]):
def execute(self, context: Context, job_id: str) -> StepDecision:
failure = context.recovery_error
assert failure is not None
return force_fail(
f"waiting for job {job_id} failed: {failure.error_type}: {failure.detail}"
)
class AwaitJob(Step[str]):
def __init__(self, jobs: FakeJobService) -> None:
self.jobs = jobs
def get_step_options(self) -> StepOptions:
return StepOptions(
execute_method_timeout=MAX_JOB_WAIT,
heartbeat_timeout=timedelta(minutes=1),
execute_retry=RetryPolicy(
initial_interval=timedelta(seconds=1),
backoff_coefficient=2.0,
maximum_attempts=3,
例子: examples/python/dex_examples/patterns/polling/polling_flow.py
// Keep pollInterval + jobCallTimeout <= HeartbeatTimeout - 10s.
// maxJobWait bounds each attempt and whether another attempt starts; Dex enforces it.
const (
pollInterval = 2 * time.Second
jobCallTimeout = 10 * time.Second
maxJobWait = 10 * time.Minute
)
var JobProgress = dex.DefineStream[JobStatus]("JobProgress", 1<<20)
type AwaitJob struct {
dex.StepDefaultsNoWaitFor[string]
jobs *FakeJobService
}
func (AwaitJob) GetStepOptions() *dex.StepOptions {
return &dex.StepOptions{
ExecuteMethodTimeout: maxJobWait,
HeartbeatTimeout: time.Minute,
ExecuteRetry: &dex.RetryPolicy{
InitialInterval: time.Second,
BackoffCoefficient: 2,
MaximumAttempts: 3,
TotalDuration: maxJobWait,
},
ExecuteFailure: dex.ProceedToOnExecuteFailure(RecordJobWaitFailure{}, nil),
}
}
func (step AwaitJob) Execute(ctx dex.Context, jobID string) (*dex.StepDecision, error) {
// Keep POLL_INTERVAL + JOB_CALL_TIMEOUT <= HeartbeatTimeout - 10s.
// MAX_JOB_WAIT bounds each attempt and whether another attempt starts; Dex enforces it.
private static final Duration POLL_INTERVAL = Duration.ofSeconds(2);
private static final Duration JOB_CALL_TIMEOUT = Duration.ofSeconds(10);
private static final Duration MAX_JOB_WAIT = Duration.ofMinutes(10);
public static final Stream<JobStatus> jobProgress =
Stream.define("JobProgress", JobStatus.class, 1L << 20);
final class AwaitJob implements Step<String> {
@Override
public Class<String> getInputType() {
return String.class;
}
@Override
public StepOptions getStepOptions() {
return StepOptions.newBuilder()
.executeMethodTimeout(MAX_JOB_WAIT)
.heartbeatTimeout(Duration.ofMinutes(1))
.executeRetry(RetryPolicy.newBuilder()
.initialInterval(Duration.ofSeconds(1))
.backoffCoefficient(2.0)
.maximumAttempts(3)
.totalDuration(MAX_JOB_WAIT)
.build())
.onExecuteFailureProceedTo(RecordJobWaitFailure.class)
.build();
}
例子: examples/java/src/main/java/io/superdurable/dex/patterns/polling/PollingFlow.java
// Keep POLL_INTERVAL_MS + JOB_CALL_TIMEOUT_MS <= heartbeatTimeoutMs - 10s.
// MAX_JOB_WAIT_MS bounds each attempt and whether another attempt starts; Dex enforces it.
const POLL_INTERVAL_MS = 2_000;
const JOB_CALL_TIMEOUT_MS = 10_000;
const MAX_JOB_WAIT_MS = 10 * 60_000;
export const jobProgress = new Stream("JobProgress", jsonCodec<JobStatus>(), 1 << 20);
class RecordJobWaitFailure implements Step<string> {
public readonly inputCodec = stringCodec;
public getStepType(): string {
return "RecordJobWaitFailure";
}
public execute(context: Context, jobId: string): StepDecision {
const failure = context.recoveryError!;
return forceFail(`waiting for job ${jobId} failed: ${failure.errorType}: ${failure.detail}`);
}
}
class AwaitJob implements Step<string> {
public readonly inputCodec = stringCodec;
public constructor(private readonly jobs: FakeJobService) {}
public getStepType(): string {
return "AwaitJob";
}
例子: examples/typescript/src/patterns/polling/polling-flow.ts
// Keep POLL_INTERVAL + JOB_CALL_TIMEOUT <= heartbeat_timeout - 10s.
// MAX_JOB_WAIT bounds each attempt and whether another attempt starts; Dex enforces it.
const POLL_INTERVAL: Duration = Duration::from_secs(2);
const JOB_CALL_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_JOB_WAIT: Duration = Duration::from_secs(10 * 60);
pub static JOB_PROGRESS: LazyLock<Stream<JobStatus>> =
LazyLock::new(|| Stream::new("JobProgress", 1 << 20));
struct AwaitJob {
jobs: Arc<FakeJobService>,
}
impl Step for AwaitJob {
type Input = String;
fn options(&self) -> StepOptions<Self::Input> {
StepOptions::new()
.execute_method_timeout(MAX_JOB_WAIT)
.heartbeat_timeout(Duration::from_secs(60))
.execute_retry(
RetryPolicy::new()
.initial_interval(Duration::from_secs(1))
.backoff_coefficient(2.0)
.maximum_attempts(3)
.total_duration(MAX_JOB_WAIT),
)
.on_execute_failure_proceed_to(&RecordJobWaitFailure)
}
比较两种轮询模式
长时间运行的 Step 加 heartbeat 更轻量。一次 Step execution 承担整个等待。
用 WaitFor Timer 轮询 会把每一轮都记录在 Flow 的历史中。你能清楚看到每一轮,也能用 Time Travel 回到某一轮。它稍微重一些。
| 行为 | WaitFor Timer | 长时间运行 Step 的 heartbeat |
|---|---|---|
| 每一轮 | Flow 历史中一次新的 Step execution | 一次尝试内的一次 heartbeat 或一条 Stream message |
| 两轮之间 | 不占用 Worker task slot | 这次尝试一直占用一个 Worker task slot |
| Dex Server failover | Timer 等待继续,不消耗重试;Worker 已收到的 WaitFor 或 Execute 尝试会失败,并消耗一次重试 | 正在运行的尝试失败,并消耗一次重试 |
| 间隔 | 整秒 | 任意间隔 |
准确的 failover 规则,包括 ASYNC 的例外,见 Lease(英文)。
间隔短、或者要最轻量的循环时,选这个模式。间隔长、要看到每一轮、或者要用 Time Travel 回到某一轮时,选 Timer 模式。Time Travel 只能回到运行近期历史窗口内的轮次;见 用 Time Travel 恢复 Flow。