等待一半完成
查看 Markdown启动 N 个 SubFlow,等待其中一半完成,然后停止尚未完成的子 Flow。
每个子 Flow 都在独立的 SubFlowStep execution 中运行。子 Flow 完成后向 SubFlowCompletedCh 发布一条消息。WaitSubFlows 等待其中一半消息,然后为每个可能尚未完成的子 Flow 发布一条 AllDoneCh 消息。
一半子 Flow 结束后,每个仍在等待的 SubFlowStep 消费一条 AllDoneCh 消息,并尝试停止自己的子 Flow。该 Step 按子 Flow ID 将结果写入 ChildStopOutcomes,然后正常完成。停止成功时记录 stopped。如果停止请求返回找不到 Flow、Flow 已非活动状态或正在关闭的类型化错误,Step 会读取子 Flow 的状态。它记录已关闭子 Flow 的最终状态和已有结果,或将仍在运行、正在关闭或找不到的子 Flow 记为 unknown,留待之后读取。其他错误由 Step 重试。
核心实现
@dataclass(frozen=True)
class ChildStopOutcome:
status: str
result: str | None = None
CHILD_STOP_OUTCOMES = AttributeMap("ChildStopOutcomes", ChildStopOutcome)
class WaitForHalfInit(Step[list[str]]):
def execute(self, context: Context, requests: list[str]) -> StepDecision:
if not requests:
return graceful_complete()
return go_to_many(
StepMovement.of(WaitSubFlows, len(requests)),
*(StepMovement.of(SubFlowStep, request) for request in requests),
)
class SubFlowStep(Step[str]):
def __init__(
self,
client_provider: Callable[[], AsyncClient],
example_subflow: ExampleSubFlow,
subflow_completed_ch: Channel[bool],
all_done_ch: Channel[bool],
) -> None:
self.client_provider = client_provider
self.example_subflow = example_subflow
self.subflow_completed_ch = subflow_completed_ch
例子: examples/python/dex_examples/patterns/parallel-subflows/wait_for_half_parent_flow.py
var (
SubFlowCompletedCh = dex.DefineChannel[bool]("SubFlowCompletedCh")
AllDoneCh = dex.DefineChannel[bool]("AllDoneCh")
ChildStopOutcomes = dex.DefineAttributeMap[ChildStopOutcome]("ChildStopOutcomes")
)
type ChildStopOutcome struct {
Status string `json:"status"`
Result *string `json:"result,omitempty"`
}
type WaitForHalfParentFlow struct {
dex.FlowDefaults
getClient func() *dex.Client
exampleFlow *ExampleSubFlow
}
func NewWaitForHalfParentFlow(getClient func() *dex.Client, exampleFlow *ExampleSubFlow) *WaitForHalfParentFlow {
return &WaitForHalfParentFlow{getClient: getClient, exampleFlow: exampleFlow}
}
func (flow *WaitForHalfParentFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(waitForHalfInit{}),
dex.DefineStep(subFlowStep{getClient: flow.getClient, exampleFlow: flow.exampleFlow}),
dex.DefineStep(waitSubFlowsStep{}),
}
}
func (*WaitForHalfParentFlow) GetPersistenceSchema() dex.PersistenceSchema {
例子: examples/go/patterns/parallel-subflows/wait_for_half_parent_flow.go
@Component
public final class WaitForHalfParentFlow implements Flow<String[]> {
public final Channel<Boolean> subFlowCompletedCh = Channel.define("SubFlowCompletedCh", Boolean.class);
public final Channel<Boolean> allDoneCh = Channel.define("AllDoneCh", Boolean.class);
public final AttributeMap<ChildStopOutcome> childStopOutcomes =
AttributeMap.define("ChildStopOutcomes", ChildStopOutcome.class);
public record ChildStopOutcome(String status, String result) {}
private final Init initStep = new Init();
private final SubFlowStep subFlowStep;
private final WaitSubFlows waitSubFlowsStep = new WaitSubFlows();
public WaitForHalfParentFlow(final ObjectProvider<Client> clientProvider) {
subFlowStep = new SubFlowStep(clientProvider);
}
public StepList<String[]> getSteps() {
return StepList.startStep(initStep).otherSteps(subFlowStep, waitSubFlowsStep);
}
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(subFlowCompletedCh, allDoneCh, childStopOutcomes);
}
final class Init implements Step<String[]> {
public Class<String[]> getInputType() { return String[].class; }
public StepDecision execute(final Context context, final String[] requests) {
if (requests.length == 0) return StepDecision.gracefulComplete(null);
final StepMovement<?>[] movements = new StepMovement<?>[requests.length + 1];
movements[0] = StepMovement.of(WaitSubFlows.class, requests.length);
例子: examples/java/src/main/java/io/superdurable/dex/patterns/parallelsubflows/WaitForHalfParentFlow.java
const subFlowCompletedCh = new Channel("SubFlowCompletedCh", booleanCodec);
const allDoneCh = new Channel("AllDoneCh", booleanCodec);
interface ChildStopOutcome {
readonly status: FlowStatus | "stopped" | "unknown";
readonly result?: string;
}
const childStopOutcomes = new AttributeMap("ChildStopOutcomes", jsonCodec<ChildStopOutcome>());
export class WaitForHalfParentFlow implements Flow<readonly string[]> {
private readonly init = new WaitForHalfInit();
private readonly subFlow: SubFlowStep;
private readonly waitSubFlows = new WaitSubFlows();
public constructor(exampleSubFlow: ExampleSubFlow) {
this.subFlow = new SubFlowStep(exampleSubFlow);
}
public getFlowType(): string { return "WaitForHalfParentFlow"; }
public getSteps() { return StepList.startStep(this.init).otherSteps(this.subFlow, this.waitSubFlows); }
public getPersistenceSchema(): PersistenceSchema { return { attributes: [childStopOutcomes], channels: [subFlowCompletedCh, allDoneCh] }; }
}
class WaitForHalfInit implements Step<readonly string[]> {
public readonly inputCodec = stringArrayCodec;
public getStepType(): string { return "Init"; }
public execute(_context: Context, requests: readonly string[]): StepDecision {
if (requests.length === 0) return gracefulComplete();
return goToMany(StepMovement.of(WaitSubFlows, requests.length), ...requests.map((request) => StepMovement.of(SubFlowStep, request)));
}
例子: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
static SUB_FLOW_COMPLETED_CH: LazyLock<Channel<bool>> =
LazyLock::new(|| Channel::new("SubFlowCompletedCh"));
static ALL_DONE_CH: LazyLock<Channel<bool>> = LazyLock::new(|| Channel::new("AllDoneCh"));
static CHILD_STOP_OUTCOMES: LazyLock<AttributeMap<ChildStopOutcome>> =
LazyLock::new(|| AttributeMap::new("ChildStopOutcomes"));
#[derive(Deserialize, Serialize)]
struct ChildStopOutcome {
status: String,
result: Option<String>,
}
#[derive(Default)]
pub struct WaitForHalfParentFlow {
init: WaitForHalfInit,
sub_flow: SubFlowStep,
wait_sub_flows: WaitSubFlows,
}
impl WaitForHalfParentFlow {
pub fn new(client: Arc<Client>) -> Self {
Self { sub_flow: SubFlowStep { client: Some(client) }, ..Self::default() }
}
}
impl Flow for WaitForHalfParentFlow {
type StartInput = Vec<String>;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.init).and(&self.sub_flow).and(&self.wait_sub_flows)
}
在阈值时刻结束的子 Flow
报告要计入每个子 Flow,或后续动作取决于每个子 Flow 怎样结束时,Step 在每次停止之后都读取子 Flow,并记录它是怎样结束的。父 Flow 只需要达到所需数量时,停止剩下的子 Flow 后直接往下走,不做这次读取。子 Flow 可能恰好在停止消息到达时结束;两者同时就绪时,Channel condition 优先于 SubFlow condition,所以 Step 可能去停止一个已经结束的子 Flow。停止成功后,或停止被拒绝(比如 "not found"、"not active" 或 "closing")后,都通过 Client 读取子 Flow。记录已关闭子 Flow 的终态和已存储的结果,让报告计入每个已经结束的子 Flow。仍在运行或正在关闭的子 Flow 稍后再读。找不到的子 Flow 按业务策略记录,比如 "unavailable"。其他停止或读取错误直接返回,让 Step 重试。每个子 Flow,无论是完成的还是被停止的,都记进同一份以 SubFlow ID 为键的记录。示例做了简化:停止成功后它不读取子 Flow 的终态。
如果每个子 Flow 都需要自己的业务身份,就把它作为顶层 Flow 启动。等待所需数量的 Step 停止每个还没报告的子 Flow;父 Flow 需要它的结局时,按那一页的规则对账。正常报告和对账得到的结果写进同一份记录,以子 Flow ID 为键。