---
title: "连同子 Flow 一起取消"
description: "当取消一个 Flow 时也必须停止它启动的子 Flow，使用这个模式。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/subflows/cancel-case/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/subflows/cancel-case.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 连同子 Flow 一起取消

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/cancel-case.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/cancel-case.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/cancel-case.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/cancel-case.rust.md)

当取消一个 Flow 时也必须停止它启动的子 Flow，使用这个模式。

例如一个贷款申请把信用检查作为子 Flow 运行。申请人撤回申请时，申请关闭，信用检查也必须停止。

父 Flow 关闭时，Dex 不会停止它的 SubFlow。父 Flow 完成、失败、超时或被停止后，SubFlow 仍会继续运行。父 Flow 必须在关闭前逐个停止子 Flow。

**Flow 图：LoanApplicationFlow**

**Step 列表**

1. `RunCreditCheck`（起始 Step）：Run the credit check child Flow, or stop it when the application is canceled. 下一步：Flow 失败，或 `AwaitUnderwriterDecision`。 读取 `applicationCanceled`；写入 `stoppedCreditCheckFlowId`。
2. `AwaitUnderwriterDecision`：Wait for the underwriter's decision or a cancellation. 下一步：Flow 失败，或 Flow 完成。 读取 `applicationCanceled`、`underwriterDecided`。

**RPC 列表**

- `cancel_application`：发布到 `applicationCanceled`。
- `decide_application`：发布到 `underwriterDecided`。

例子: [examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py)

## 工作方式

- 取消 RPC 把原因发布到一个取消 Channel。
- 启动 SubFlow 的 Step 用 `AnyOf` 同时等待 SubFlow 和取消 Channel。
- 如果子 Flow 先成功完成，`Execute` 读取它的结果并继续。子 Flow 以其他方式结束时，例如失败或超时，父 Flow 用 `ForceFail` 失败。
- 如果取消消息胜出，`Execute` 用 `SubFlowID` 读取子 Flow ID，用 Client 的 `StopFlow` 停止子 Flow，再用 `ForceFail` 关闭父 Flow。
- 之后每个需要等待的 Step 也同时等待取消 Channel。子 Flow 结束后才到达的取消，仍然能关闭这个 case。
- 在每个等待中，已经到达的取消都优先于正常完成。等待 SubFlow 时，已就绪的 Channel 总是优先于已就绪的 SubFlow。等待两个 Channel 时，先声明的 Channel 胜出，所以把取消 Channel 声明在决定 Channel 之前。
- 兜底或截止 Timer 可能胜出，而撤回仍可能在它之后、Timer 分支运行之前提交。Timer 分支要处理可能仍在排队的撤回，例如在下一个 Step 里继续等待取消 Channel。也可以用 Attribute 锁关闭回复窗口，见[带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md#close-the-response-window)。
- 如果最后一个 Step 已经消费了它的决定消息，或者 Flow 已经关闭，之后到达的取消不能再改变结果。
- 决定最终确定后，关闭 Flow 时不要消费取消 Channel。如果关闭时排空取消 Channel 并回退到取消路径，晚到的取消就会推翻决定。

在示例中：

1. 申请人通过 `cancelApplication` RPC 撤回申请。RPC 把原因发布到 `ApplicationCanceled` Channel。
2. `RunCreditCheck` 把信用检查作为子 Flow 启动，超时时间为 7 天。它等待撤回，或者等待信用检查结束。
3. 如果申请人先撤回，`RunCreditCheck` 停止信用检查，并带着原因让申请失败。
4. 如果信用检查先成功完成，申请带着报告进入 `AwaitUnderwriterDecision`。信用检查失败或超时时，申请失败。
5. `AwaitUnderwriterDecision` 等待撤回或审批人的决定。它先声明撤回 Channel，所以撤回和决定同时就绪时撤回胜出。撤回让申请失败，决定让申请完成。

## 停止子 Flow

- `Execute` 可能被重试，子 Flow 也可能恰好同时结束。把 `StopFlow` 返回的“未找到”“不活跃”和“正在关闭”都当作已经停止。
- Worker 需要一个 Client 才能调用 `StopFlow`。把 Client provider 传给 Flow 的构造函数。
- 如果运维人员或测试需要找到被停止的子 Flow，把它的 Flow ID 记录在 Attribute 中。

## 限制

只有取消通过取消 Channel 到达时，这个模式才会停止子 Flow。父 Flow 以其他方式关闭时，子 Flow 会继续运行：

- 对父 Flow 调用 Client 的 `StopFlow`；
- 父 Flow 的 Flow timeout；
- 父 Flow 中另一个 Step 返回的 `ForceFail` 或 `ForceComplete`。

给每个子 Flow 设置 Flow timeout，这样即使没有人停止它，它也会结束。示例给信用检查设置了 7 天的 timeout。客户端取消 case 时调用取消 RPC，而不是 `StopFlow`。

## 多个子 Flow

一条取消消息只满足一个等待。如果多个 Step 同时各自持有一个子 Flow，每个 Step 都需要自己的取消消息。

- 使用 ChannelMap，每个 Step 一个 key。取消 RPC 向每个 key 发布，每个 Step 等待自己的 key。
- 或者让取消 RPC 向同一个 Channel 为每个等待中的 Step 各发布一条消息。

在 Flow 被关闭之前，每个持有子 Flow 的 Step 都必须先停止自己的子 Flow。如果在第一个看到取消消息的 Step 中关闭 Flow，它的 `ForceFail` 会在其他 Step 停止各自子 Flow 之前取消它们。

## 示例

`LoanApplicationFlow` 以申请人 ID 启动。`RunCreditCheck` 以 7 天的 Flow timeout 启动 `CreditCheckFlow`，并等待它或 `cancelApplication` RPC。`AwaitUnderwriterDecision` 等待 `decideApplication` RPC 或之后到达的取消。取消停止了信用检查时，Flow 把子 Flow ID 存入 `stoppedCreditCheckFlowId` Attribute。

**Python**

```python
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]
        self, context: AsyncContext, application: LoanApplication
    ) -> StepDecision:
        reasons = APPLICATION_CANCELED.results(context)
        if reasons:
            child_flow_id = SubFlow.get_flow_id(context)
            await self.stop_credit_check(child_flow_id)
            STOPPED_CREDIT_CHECK_FLOW_ID.set(context, child_flow_id)
            return force_fail(APPLICATION_CANCELED_PREFIX + reasons[0])
        result = SubFlow.get_condition_results(context)
        if result.status is not FlowStatus.COMPLETED:
            return force_fail(f"credit check ended with status {result.status.value}")
        return go_to(AwaitUnderwriterDecision, result.single_output(str))

    async def stop_credit_check(self, child_flow_id: str) -> None:
        """Cancels the child; a missing or already closed child counts as stopped."""
        try:
            await self.client_provider().stop_flow(
                child_flow_id,
                StopFlowOptions(type=StopType.CANCEL, reason="loan application canceled"),
            )
        except (FlowNotFoundError, FlowNotActiveOrNotFoundError, FlowClosingError):
            return


class AwaitUnderwriterDecision(Step[str]):
    """Also waits for the cancel Channel, so a late cancellation still closes the application."""

    def wait_for(self, context: Context, report: str) -> Wait:
        return Wait.any_of(APPLICATION_CANCELED.for_one(), UNDERWRITER_DECIDED.for_one())

    def execute(self, context: Context, report: str) -> StepDecision:
        reasons = APPLICATION_CANCELED.results(context)
        if reasons:
            return force_fail(APPLICATION_CANCELED_PREFIX + reasons[0])
        decisions = UNDERWRITER_DECIDED.results(context)
        return graceful_complete(f"{decisions[0]} after {report}")
```

例子: [examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py)

## 下一步

- [有业务标识的子 Flow](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/child-flows-with-business-identity.md)
- [持久化定时器](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer.md)
- [SubFlow](https://docs.superdurable.io/zh-Hans/concepts/primitives/subflow.md)
- [Channel](https://docs.superdurable.io/zh-Hans/concepts/primitives/channel.md)
- [SubFlow](https://docs.superdurable.io/zh-Hans/design-patterns/subflows.md)
- [Workflow Patterns 评估：WCP-20 Cancel Case](https://docs.superdurable.io/zh-Hans/correctness-and-expressiveness/workflow-patterns.md#wcp-20)
