首个获胜的并行 Step
查看 Markdown同时运行多个 Step,采用第一个结果,取消其余的。第一个可接受的结果就够用时使用,例如在几个报价服务中取最快的一个。
工作方式
InitStep 启动多个 DoWork execution。每个 execution 随机等待一小段时间,所以任何一个都可能最先完成。Dex 最先提交的 decision 保留它的结果,并取消其他 DoWork sibling execution。
每个分支都是独立的 Step execution,有自己的重试、失败路由和持久结果。如果 Dex 需要单独重试或取消某个分支,或单独记录分支结果,就使用独立的 Step 或子 Flow。在一个 Execute 里用进程内并发(例如 Promise.any、asyncio task 或线程),Dex 重试的是整个 Execute,所有调用会一起重跑。它适合一起成功或一起重试的幂等读取。
核心实现
每个 DoWork 在同一个 decision 里完成,并取消它的 sibling DoWork execution。
class DoWork(Step[int]):
async def execute( # type: ignore[override]
self, context: AsyncContext, input: int
) -> StepDecision:
await asyncio.sleep(random.uniform(0.05, 0.5))
return graceful_complete(input).with_canceling_sibling_steps(DoWork)
class InitStep(Step[int]):
def execute(self, context: Context, input: int) -> StepDecision:
return go_to_many(
*(StepMovement.of(DoWork, index) for index in range(input))
)
例子: examples/python/dex_examples/patterns/parallel/first_win_parallel_steps_flow.py
type firstWinInit struct{ dex.StepDefaultsNoWaitFor[int] }
func (firstWinInit) GetStepType() string { return "Init" }
func (firstWinInit) Execute(_ dex.Context, count int) (*dex.StepDecision, error) {
movements := make([]dex.StepMovement, 0, count)
for index := 0; index < count; index++ {
movements = append(movements, dex.MovementOf(firstWinWork{}, index))
}
return dex.GoToMany(movements...), nil
}
type firstWinWork struct{ dex.StepDefaultsNoWaitFor[int] }
func (firstWinWork) GetStepType() string { return "DoWork" }
func (firstWinWork) Execute(_ dex.Context, index int) (*dex.StepDecision, error) {
time.Sleep(time.Duration(50+rand.Intn(450)) * time.Millisecond)
return dex.GracefulComplete(index).CancelSiblingSteps(firstWinWork{}), nil
}
final class InitStep implements Step<Integer> {
@Override
public Class<Integer> getInputType() {
return Integer.class;
}
@Override
public StepDecision execute(final Context context, final Integer count) {
final StepMovement<?>[] movements = new StepMovement<?>[count];
for (int index = 0; index < count; index++) {
movements[index] = StepMovement.of(DoWork.class, index);
}
return StepDecision.goToMany(movements);
}
}
final class DoWork implements Step<Integer> {
@Override
public Class<Integer> getInputType() {
return Integer.class;
}
@Override
public StepDecision execute(final Context context, final Integer input) {
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(50, 500));
} catch (final InterruptedException error) {
Thread.currentThread().interrupt();
throw new IllegalStateException(error);
}
return StepDecision.gracefulComplete(input)
.withCancelingSiblingSteps(DoWork.class);
}
}
例子: examples/java/src/main/java/io/superdurable/dex/patterns/parallel/FirstWinParallelStepsFlow.java
class FirstWinDoWork implements Step<number> {
public readonly inputCodec = doubleCodec;
public getStepType(): string {
return "DoWork";
}
public async execute(_context: Context, input: number): Promise<StepDecision> {
await new Promise<void>((resolve) => {
setTimeout(resolve, 50 + Math.floor(Math.random() * 450));
});
return withCancelingSiblingSteps(gracefulComplete(input), FirstWinDoWork);
}
}
class FirstWinInit implements Step<number> {
public readonly inputCodec = doubleCodec;
public getStepType(): string {
return "Init";
}
public execute(_context: Context, count: number): StepDecision {
return goToMany(
...Array.from({ length: count }, (_, index) =>
StepMovement.of(FirstWinDoWork, index),
),
);
}
}
例子: examples/typescript/src/patterns/parallel/parallel-step-flows.ts
#[derive(Default)]
struct FirstWinInit;
impl Step for FirstWinInit {
type Input = usize;
fn step_type(&self) -> &'static str {
"InitStep"
}
fn execute(&self, _: &mut Context, count: usize) -> HandlerResult<StepDecision> {
Ok(StepDecision::go_to_many(
(0..count).map(|index| StepMovement::to(&FirstWinWork, index)),
))
}
}
#[derive(Default)]
struct FirstWinWork;
impl Step for FirstWinWork {
type Input = usize;
fn step_type(&self) -> &'static str {
"DoWork"
}
fn execute(&self, _: &mut Context, input: usize) -> HandlerResult<StepDecision> {
thread::sleep(Duration::from_millis(fastrand::u64(50..500)));
Ok(StepDecision::graceful_complete(input).cancel_sibling_step(&FirstWinWork))
}
}
例子: examples/rust/src/patterns/parallel/parallel_step_flows.rs
规则和陷阱
- 取消选择器只取消同一 Step 类型的 sibling execution。其他分支继续运行。
- 每个落败的 execution 都要关注它所在 Step 的取消信号。支持取消的调用,把信号传给它。其他调用设置较短的超时,并在调用之间检查信号。
- 取消是协作式的,不会撤销已经发生的外部效果。已经生效的预留,用一次独立、有界、幂等的调用撤回。必须释放的预留,使用会到期的租约,或以业务 ID 为键的持久补偿分支。