连同子 Flow 一起取消
查看 Markdown当取消一个 Flow 时也必须停止它启动的子 Flow,使用这个模式。父 Flow 完成、失败、超时或被停止后,SubFlow 仍会继续运行,所以父 Flow 必须在关闭前逐个停止子 Flow。
工作方式
示例是一个贷款申请,它把信用检查作为子 Flow 运行。申请人撤回申请时,申请关闭,信用检查也随之停止。
- 取消 RPC 把原因发布到一个取消 Channel。这里
cancelApplication发布到ApplicationCanceled。 - 启动 SubFlow 的 Step 用
AnyOf同时等待 SubFlow 和取消 Channel。RunCreditCheck以 7 天的 Flow timeout 启动信用检查。 - 如果子 Flow 先成功完成,
Execute读取它的结果并进入AwaitUnderwriterDecision。子 Flow 以其他方式结束时,例如失败或超时,父 Flow 用ForceFail失败。 - 如果取消消息胜出,
Execute用SubFlowID读取子 Flow ID,用 Client 的StopFlow停止子 Flow,再用ForceFail关闭父 Flow。 - 之后每个需要等待的 Step 也同时等待取消 Channel。所以子 Flow 结束后才到达的取消,仍然能关闭这个 case。
AwaitUnderwriterDecision收到取消时让申请失败,收到审批人的决定时让申请完成。
核心实现
在 RunCreditCheck 中注意两点:两者同时就绪时,无论声明顺序如何,取消 Channel 都优先于子 Flow 的 SubFlow condition;stopCreditCheck 把已经不存在的子 Flow 当作已经停止。
class RunCreditCheck(Step[LoanApplication]):
"""Waits for its child Flow or a cancellation, whichever comes first."""
def __init__(
self,
client_provider: Callable[[], AsyncClient],
credit_check_flow: CreditCheckFlow,
) -> None:
self.client_provider = client_provider
self.credit_check_flow = credit_check_flow
def wait_for(self, context: Context, application: LoanApplication) -> Wait:
request = CreditCheckRequest(
applicant_id=application.applicant_id,
report_delay_seconds=application.credit_report_delay_seconds,
)
# The cancel condition comes first: it wins when both are ready.
return Wait.any_of(
APPLICATION_CANCELED.for_one(),
SubFlow.run(
self.credit_check_flow,
request,
SubFlowOptions(
timeout=CREDIT_CHECK_TIMEOUT,
reuse_policy=SubFlowReusePolicy.RESTART_IF_PREVIOUS_EXITS_ABNORMALLY,
),
),
)
async def execute( # type: ignore[override]
例子: examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py
// RunCreditCheck waits for its child Flow or a cancellation, whichever comes first.
type RunCreditCheck struct {
dex.StepDefaults
getClient func() *dex.Client
creditCheckFlow *CreditCheckFlow
}
func (step RunCreditCheck) WaitFor(_ dex.Context, application LoanApplication) (*dex.Wait, error) {
timeout := CreditCheckTimeout
request := CreditCheckRequest{
ApplicantID: application.ApplicantID,
ReportDelaySeconds: application.CreditReportDelaySeconds,
}
// The cancel condition comes first: it wins when both are ready.
return dex.AnyOf(
ApplicationCanceled.ForOne(),
dex.SubFlow(step.creditCheckFlow, request, dex.SubFlowOptions{
Timeout: &timeout,
ReusePolicy: dex.RestartSubFlowIfPreviousExitedAbnormally,
}),
), nil
}
func (step RunCreditCheck) Execute(ctx dex.Context, _ LoanApplication) (*dex.StepDecision, error) {
reasons, err := ApplicationCanceled.GetConditionResults(ctx)
if err != nil {
return nil, err
}
if len(reasons) > 0 {
childFlowID, err := dex.SubFlowID(ctx)
/** Waits for its child Flow or a cancellation, whichever comes first. */
static final class RunCreditCheck implements Step<LoanApplication> {
private final ObjectProvider<Client> clientProvider;
RunCreditCheck(final ObjectProvider<Client> clientProvider) {
this.clientProvider = clientProvider;
}
@Override
public Class<LoanApplication> getInputType() {
return LoanApplication.class;
}
@Override
public Wait waitFor(final Context context, final LoanApplication application) {
final CreditCheckRequest request = new CreditCheckRequest(
application.applicantId(), application.creditReportDelaySeconds());
// The cancel condition comes first: it wins when both are ready.
return Wait.anyOf(
applicationCanceled.forOne(),
SubFlow.run(CreditCheckFlow.class, request, SubFlowOptions.newBuilder()
.timeout(CREDIT_CHECK_TIMEOUT)
.reusePolicy(SubFlowReusePolicy.RESTART_IF_PREVIOUS_EXITS_ABNORMALLY)
.build()));
}
@Override
public StepDecision execute(final Context context, final LoanApplication application) {
final List<String> reasons = applicationCanceled.getConditionResults(context);
if (!reasons.isEmpty()) {
例子: examples/java/src/main/java/io/superdurable/dex/patterns/cancelcase/LoanApplicationFlow.java
/** Waits for its child Flow or a cancellation, whichever comes first. */
class RunCreditCheck implements Step<LoanApplication> {
public constructor(
private readonly getClient: () => Client,
private readonly creditCheckFlow: CreditCheckFlow,
) {}
public getStepType(): string {
return "RunCreditCheck";
}
public waitFor(_context: Context, application: LoanApplication): Wait {
// The cancel condition comes first: it wins when both are ready.
return Wait.anyOf(
applicationCanceled.forOne(),
SubFlow.run(
this.creditCheckFlow,
{
applicantId: application.applicantId,
reportDelaySeconds: application.creditReportDelaySeconds,
},
{
timeoutMs: CREDIT_CHECK_TIMEOUT_MS,
reusePolicy: SubFlowReusePolicy.RESTART_IF_PREVIOUS_EXITS_ABNORMALLY,
},
),
);
}
public async execute(context: Context, _application: LoanApplication): Promise<StepDecision> {
例子: examples/typescript/src/patterns/cancel-case/loan-application-flow.ts
/// Waits for its child Flow or a cancellation, whichever comes first.
#[derive(Default)]
pub struct RunCreditCheck {
client: Option<Arc<Client>>,
}
impl RunCreditCheck {
/// Cancels the child; a missing or already closed child counts as stopped.
fn stop_credit_check(&self, child_flow_id: &str) -> HandlerResult<()> {
let client = self
.client
.as_ref()
.ok_or_else(|| HandlerError::new("ClientUnavailable", "the Dex Client is not ready"))?;
match client.stop_flow(
child_flow_id,
StopFlowOptions::cancel().reason("loan application canceled"),
) {
Ok(())
| Err(
SdkError::FlowNotFound { .. }
| SdkError::FlowNotActiveOrNotFound { .. }
| SdkError::FlowClosing { .. },
) => Ok(()),
Err(error) => Err(HandlerError::from_error(error)),
}
}
}
impl Step for RunCreditCheck {
type Input = LoanApplication;
晚到和竞争的取消
- 在每个等待中,已经到达的取消都优先于正常完成。把取消 Channel 声明在决定 Channel 之前,因为多个 Channel 同时就绪时,先声明的胜出。已就绪的 Channel 本来就优先于已就绪的 SubFlow,见 Condition results 中的 AnyOf 顺序。
- 兜底或截止 Timer 可能胜出,而取消仍可能在它之后、Timer 分支运行之前提交。Timer 分支要处理可能仍在排队的取消,例如在下一个 Step 里继续等待取消 Channel。也可以用 Attribute 锁关闭回复窗口,见回应窗口。
- 决定最终确定后,关闭 Flow 时不消费取消 Channel。如果最后一个 Step 已经消费了它的决定消息,或者 Flow 已经关闭,之后到达的取消不能再改变结果。如果关闭时排空取消 Channel 并回退到取消路径,晚到的取消就会推翻决定。
停止子 Flow
Execute可能被重试,子 Flow 也可能恰好同时结束。把StopFlow返回的“未找到”“不活跃”和“正在关闭”都当作已经停止。- Worker 需要一个 Client 才能调用
StopFlow。把 Client provider 传给 Flow 的构造函数。 - 如果运维人员或测试需要找到被停止的子 Flow,把它的 Flow ID 记录在 Attribute 中。示例用的是
stoppedCreditCheckFlowId。
多个子 Flow
一条取消消息只满足一个等待。如果多个 Step 同时各自持有一个子 Flow,每个 Step 都需要自己的取消消息。
- 使用 ChannelMap,每个 Step 一个 key。取消 RPC 向每个 key 发布,每个 Step 等待自己的 key。
- 或者让取消 RPC 向同一个 Channel 为每个等待中的 Step 各发布一条消息。
在 Flow 被关闭之前,每个持有子 Flow 的 Step 都必须先停止自己的子 Flow。如果第一个看到取消消息的 Step 关闭 Flow,它的 ForceFail 会在其他 Step 停止各自子 Flow 之前取消它们。
限制
只有取消通过取消 Channel 到达时,这个模式才会停止子 Flow。父 Flow 以其他方式关闭时,子 Flow 会继续运行:
- 对父 Flow 调用 Client 的
StopFlow; - 父 Flow 的 Flow timeout;
- 父 Flow 中另一个 Step 返回的
ForceFail或ForceComplete。
所以客户端取消 case 时调用取消 RPC,而不是 StopFlow。子 Flow 必须在启动时已知的期限内结束时,给它设置 Flow timeout,这样即使没有人停止它,它也会结束。