等待并行 Step
查看 Markdown等所有并行分支都结束后再继续。后面的 Step 需要所有分支的结果时使用,例如把它们合成一个回复。
Join 的工作方式
InitStep 用 parallel-complete 这个 Join 开启一轮。这次 fork 在同一个 decision 里为每一项启动一个 DoWork execution,并启动 Await Step。它们拿到同一个 round token:round key 和分支数。每个 DoWork 随机等待一小段时间,然后结束自己的分支,并上报自己的序号。Await 在 WaitFor 中等待这一轮的全部分支。
Join 是一个有名字的 ChannelMap,存放分支结果。它计数的是分支上报的结果,而不是观察分支 Step 本身。结果是持久化的,因此即使结果在 Await 开始等待之前上报,也仍然会被计入。每一轮的结果只计入这一轮。汇合 Step 的等待是普通的条件,可以和 Timer 组合。
当工作在子 Flow 中运行时,用 AllOf 等待 SubFlow 就是原生的汇合。
核心实现
@dataclass(frozen=True)
class WorkItem:
index: int
round: JoinRound
def build_work_item(index: int) -> Callable[[JoinRound], StepMovement[WorkItem]]:
return lambda join_round: StepMovement.of(DoWork, WorkItem(index, join_round))
class DoWork(Step[WorkItem]):
def __init__(self, work_completed: Join[int]) -> None:
self.work_completed = work_completed
async def execute( # type: ignore[override]
self, context: AsyncContext, input: WorkItem
) -> StepDecision:
await asyncio.sleep(random.uniform(0.05, 0.5))
return self.work_completed.end_branch(context, input.round, input.index)
class Await(Step[JoinRound]):
def __init__(self, work_completed: Join[int]) -> None:
self.work_completed = work_completed
def wait_for(self, context: Context, input: JoinRound) -> Wait:
return Wait.until(self.work_completed.for_all_branches(input))
def execute(self, context: Context, input: JoinRound) -> StepDecision:
return graceful_complete(
len(self.work_completed.branch_results(context, input))
)
class InitStep(Step[int]):
def __init__(self, work_completed: Join[int]) -> None:
self.work_completed = work_completed
def execute(self, context: Context, input: int) -> StepDecision:
return go_to_many(
*self.work_completed.fork(
context,
[build_work_item(index) for index in range(input)],
lambda join_round: StepMovement.of(Await, join_round),
)
)
例子: examples/python/dex_examples/patterns/parallel/await_parallel_steps_flow.py
var WorkCompletedJoin = dex.DefineJoin[int]("parallel-complete")
type awaitInit struct{ dex.StepDefaultsNoWaitFor[int] }
func (awaitInit) GetStepType() string { return "Init" }
func (awaitInit) Execute(ctx dex.Context, count int) (*dex.StepDecision, error) {
branchBuilders := make([]func(dex.JoinRound) dex.StepMovement, 0, count)
for index := range count {
branchBuilders = append(branchBuilders, func(round dex.JoinRound) dex.StepMovement {
return dex.MovementOf(awaitWork{}, WorkItem{Index: index, Round: round})
})
}
movements, err := WorkCompletedJoin.Fork(ctx, branchBuilders, func(round dex.JoinRound) dex.StepMovement {
return dex.MovementOf(awaitStep{}, round)
})
if err != nil {
return nil, err
}
return dex.GoToMany(movements...), nil
}
// WorkItem is the input of one DoWork branch.
type WorkItem struct {
Index int `json:"index"`
Round dex.JoinRound `json:"round"`
}
type awaitWork struct {
dex.StepDefaultsNoWaitFor[WorkItem]
public final Join<Integer> workCompleted = Join.define("parallel-complete", Integer.class);
/** One worker: its index and the Join round it reports to. */
public record WorkItem(int index, JoinRound round) {
}
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 List<Function<JoinRound, StepMovement<?>>> workers =
new ArrayList<Function<JoinRound, StepMovement<?>>>();
for (int index = 0; index < count; index++) {
final int workIndex = index;
workers.add(round -> StepMovement.of(DoWork.class, new WorkItem(workIndex, round)));
}
return StepDecision.goToMany(workCompleted.fork(
context, workers, round -> StepMovement.of(Await.class, round)));
}
}
final class DoWork implements Step<WorkItem> {
@Override
public Class<WorkItem> getInputType() {
return WorkItem.class;
}
例子: examples/java/src/main/java/io/superdurable/dex/patterns/parallel/AwaitParallelStepsFlow.java
const workCompleted = new Join("parallel-complete", doubleCodec);
interface WorkItem {
readonly index: number;
readonly round: JoinRound;
}
class AwaitDoWork implements Step<WorkItem> {
public getStepType(): string {
return "DoWork";
}
public async execute(context: Context, item: WorkItem): Promise<StepDecision> {
await new Promise<void>((resolve) => {
setTimeout(resolve, 50 + Math.floor(Math.random() * 450));
});
return workCompleted.endBranch(context, item.round, item.index);
}
}
class Await implements Step<JoinRound> {
public readonly inputCodec = joinRoundCodec;
public getStepType(): string {
return "Await";
}
public waitFor(_context: Context, round: JoinRound): Wait {
return Wait.until(workCompleted.forAllBranches(round));
}
public execute(context: Context, round: JoinRound): StepDecision {
return gracefulComplete(workCompleted.branchResults(context, round).length);
}
}
class AwaitInit implements Step<number> {
public readonly inputCodec = doubleCodec;
public getStepType(): string {
return "Init";
}
public execute(context: Context, count: number): StepDecision {
return goToMany(
...workCompleted.fork(
context,
Array.from({ length: count }, (_, index) => (round: JoinRound) =>
StepMovement.of(AwaitDoWork, { index, round }),
),
(round) => StepMovement.of(Await, round),
),
);
}
}
例子: examples/typescript/src/patterns/parallel/parallel-step-flows.ts
#[derive(Default)]
struct AwaitInit;
impl Step for AwaitInit {
type Input = usize;
fn step_type(&self) -> &'static str {
"InitStep"
}
fn execute(&self, context: &mut Context, count: usize) -> HandlerResult<StepDecision> {
let branches = (0..count)
.map(|index| {
Box::new(move |round: &JoinRound| {
StepMovement::to(
&AwaitWork,
WorkItem {
index,
round: round.clone(),
},
)
}) as Box<dyn FnOnce(&JoinRound) -> StepMovement>
})
.collect();
let movements =
COMPLETE.fork(context, branches, |round| StepMovement::to(&Await, round))?;
Ok(StepDecision::go_to_many(movements))
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkItem {
pub index: usize,
pub round: JoinRound,
例子: examples/rust/src/patterns/parallel/parallel_step_flows.rs
规则和陷阱
- 汇合 Step 要和各分支在同一次 fork 中启动。使用隐式 round key 时,一个 Step 方法里同一个 Join 最多 fork 一次。显式 round key 和 RPC fork 见 Join 参考。
- 每个分支每轮恰好上报一个结果,Flow 仍然打开时的所有退出路径都要上报,包括失败路由去往的 Step。从不上报的分支会让汇合一直等下去。上报两次的分支会被计两次。
- 由多个 Step 组成的分支,要把 round token 一直传到最后一个 Step,并且只由这个 Step 上报。
- 分支自己不等待汇合。只有汇合 Step 等待它这一轮。
- 被取消的分支不再上报,所以要么把汇合和它等待的分支一起取消,要么用
AnyOf同时等待汇合和一个 Timer。 - 通过 Join 的 ChannelMap 读取一轮中待处理的结果,例如在 RPC 中读取。不要直接向它发布消息。
- 汇合 Step 的等待已经消费了结果之后被取消时,这些结果按被取消的 Step 的规则处理。
只等待部分分支
汇合 Step 也可以只等待第一个分支,或者等待 n 个分支。然后它要么取消其余分支,要么让它们继续运行。
要取消,汇合 Step 返回一个取消 sibling Step 的 decision。fork 把分支和汇合一起启动,所以这些 sibling 是那次 fork 启动的 Step。它们不包括多 Step 分支里后面的 Step;RPC fork 的分支要按 Step 类型取消,见 Join 参考(英文)。每个分支处理它所在 Step 的取消信号,做法同首个获胜的并行 Step。带取消的汇合,它的那一轮永远不复位,因为被取消的分支不会上报。在循环中,下一轮直接 fork 新的一轮。
如果其余分支继续运行,它们的结果会晚到。在循环中,下一轮的拆分 Step 先复位上一轮:它的 WaitFor 等待剩下的结果,它的 Execute 可以读取这些结果。然后它 fork 下一轮。如果不复位,晚到的结果会一直待处理,直到 Flow 关闭。
边界情况见 Join 参考。Workflow Patterns 评估链接了这两种写法的可运行示例。