---
title: "用户入驻流程"
description: "新用户注册后先验证邮箱，再按顺序完成两个设置任务。某个阶段在等用户操作时，Flow 会发送提醒。"
canonical_url: "https://docs.superdurable.io/zh-Hans/examples/user-onboarding-process/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/use-cases/user-onboarding-process.mdx"
locale: "zh-Hans"
language: "python"
---

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

# 用户入驻流程

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

新用户注册后先验证邮箱，再按顺序完成两个设置任务。某个阶段在等用户操作时，Flow 会发送提醒。

**SDK：** Python · Go · TypeScript · Java · Rust

**展示：**[提醒](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/reminder.md)。

**Flow 图：UserOnboardingFlow**

**Step 列表**

1. `Submit`（起始 Step）：Store the sign-up form and send the verification email. 下一步：`VerifyEmail`。 写入 `Form`。
2. `AccomplishTask1`：Wait for the user to finish task 1 and send a reminder when it is late. 下一步：`AccomplishTask2`，或 `AccomplishTask1`（再次）。 读取 `Form`、`Task1Completed`；写入 `Status`。
3. `AccomplishTask2`：Wait for the user to finish task 2, then complete onboarding. 下一步：Flow 完成，或 `AccomplishTask2`（再次）。 读取 `Form`、`Task2Completed`；写入 `Status`。
4. `VerifyEmail`：Wait for email verification and send a reminder when it is late. 下一步：`AccomplishTask1`，或 `VerifyEmail`（再次）。 读取 `Form`、`VerifyEmail`；写入 `Status`。

**RPC 列表**

- `accomplish_task_1`：读取 `Status`；发布到 `Task1Completed`。
- `accomplish_task_2`：读取 `Status`；发布到 `Task2Completed`。
- `verify`：读取 `Status`；发布到 `VerifyEmail`。

例子: [examples/python/dex_examples/products/signup/user_signup_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/signup/user_signup_flow.py)

<a id="product-requirements"></a>

## 产品需求

<a id="产品需求"></a>

- 用户名就是 Flow ID。同一个用户名再次注册不会启动第二个 Flow，启动端点会报告该入驻流程已经存在。
- 各阶段按固定顺序进行：验证邮箱、完成任务 1、完成任务 2。之后 Flow 发送欢迎邮件并完成。
- 用户操作之前，每个阶段在示例中每 24 秒发送一次提醒。
- 应用通过三个 RPC 推进各阶段：验证邮箱、完成任务 1、完成任务 2。在错误阶段调用的 RPC 不做任何改动，只返回一条回复，例如 `task 1 is not waiting`。
- 一直不完成的用户会持续收到提醒，直到 Flow 完成、被取消或达到 Flow 超时。

<a id="flow-design"></a>

## Flow 设计

<a id="flow-设计"></a>

**Submit** 保存表单，发送验证邮件，然后转到 `VerifyEmail`。之后 `VerifyEmail`、`AccomplishTask1` 和 `AccomplishTask2` 依次等待用户操作。

每个等待 Step 用 `AnyOf` 让 24 秒的 Timer 和自己的 Channel 竞争。Channel 消息先到时，`Execute` 进入下一阶段。Timer 先触发时，`Execute` 发送提醒并回到同一个 Step，由它启动新的 Timer。

这个 Flow 由两个选择决定：

- **每个阶段一个 Channel。** `VerifyEmail`、`Task1Completed` 和 `Task2Completed` 互相独立，所以一次用户操作只唤醒等待它的那个 Step。
- **阶段记录在 `Status` Attribute 里。** 每个 `WaitFor` 设置它，这个值随 `WaitFor` 的结果一起保存。RPC 读取它，拒绝在错误阶段到达的操作。

真实的邮件调用需要[幂等键](https://docs.superdurable.io/zh-Hans/concepts/step.md#idempotency-keys)，因为被中断的 Step 可能再次运行。示例都没有传。Python、Go、Java 和 TypeScript 的邮件发送是桩实现，Rust 示例则只记录事件。

<a id="core-implementation"></a>

## 核心实现

<a id="核心实现"></a>

第一段代码声明 Flow。第二段展示 `AccomplishTask1` Step；Python 标签页还展示向它的 Channel 发布消息的 RPC。Rust 示例只接收邮箱作为输入，并记录事件，而不是发送邮件。每个链接的示例还包含 RPC、HTTP controller 和集成测试。

**Python**

```python
class UserOnboardingFlow(Flow[SignupForm]):
    form = Attribute("Form", SignupForm)
    status = Attribute("Status", str)
    verify_email = Channel[None]("VerifyEmail", type(None))
    task_1_completed = Channel[None]("Task1Completed", type(None))
    task_2_completed = Channel[None]("Task2Completed", type(None))

    def __init__(self, service: MyDependencyService) -> None:
        self.service = service
        self.verify_step = VerifyEmail(service, self.form, self.verify_email, self.status)
        self.task_1_step = AccomplishTask1(
            service,
            self.form,
            self.status,
            self.task_1_completed,
        )
        self.task_2_step = AccomplishTask2(
            service,
            self.form,
            self.status,
            self.task_2_completed,
        )
        self.submit = Submit(service, self.form, self.status, self.verify_step)

    def get_steps(self) -> StepList[SignupForm]:
        return StepList.start_step(self.submit).other_steps(
            self.verify_step,
            self.task_1_step,
            self.task_2_step,
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(
            self.form,
            self.status,
            self.verify_email,
            self.task_1_completed,
            self.task_2_completed,
        )
```

```python
class AccomplishTask1(Step[None]):
    def __init__(
        self,
        service: MyDependencyService,
        form: Attribute[SignupForm],
        status: Attribute[str],
        task_1_completed: Channel[None],
    ) -> None:
        self.service = service
        self.form = form
        self.status = status
        self.task_1_completed = task_1_completed

    def wait_for(self, context: Context, input: None) -> Wait:
        self.status.set(context, "waiting_for_task_1")
        return Wait.any_of(
            Timer.by_duration(timedelta(seconds=24)),
            self.task_1_completed.for_one(),
        )

    def execute(self, context: Context, input: None) -> StepDecision:
        signup_form = self.form.get(context)
        if self.task_1_completed.results(context):
            self.service.send_email(
                signup_form.email,
                "complete onboarding task 2",
                "task 2 is ready",
            )
            return go_to(AccomplishTask2, None)
        self.service.send_email(
            signup_form.email,
            "task 1 reminder",
            "please complete onboarding task 1",
        )
        return go_to(AccomplishTask1, None)
```

```python
@rpc
def accomplish_task_1(self, context: Context) -> RPCResult[str]:
    if self.status.get(context) != "waiting_for_task_1":
        return RPCResult("task 1 is not waiting")
    self.task_1_completed.publish(context, None)
    return RPCResult("task 1 accomplished")
```

例子: [examples/python/dex_examples/products/signup/user_signup_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/signup/user_signup_flow.py)

<a id="run-it"></a>

## 运行

<a id="demo"></a>

<a id="演示"></a>

按[在 playground 里运行一个示例](https://docs.superdurable.io/zh-Hans/install.md#run-an-example-from-the-playground)启动一种语言的示例。在[示例 playground](https://github.com/superdurable/dex/tree/main/examples/playground) 中选择 **User onboarding process**。用一个 `username` 调用 **Submit**，这个 username 就是 Flow ID。然后用同一个 `username` 依次调用 **Verify**、**Accomplish task 1** 和 **Accomplish task 2**。

每次调用之前，先等 Dex Web 中的 `Status` Attribute 显示这次调用需要的阶段：`waiting_for_verification`、`waiting_for_task_1` 或 `waiting_for_task_2`。调用来得太早时不做任何改动，只返回一条回复，例如 `task 1 is not waiting`。等状态变化后再调用一次。

Rust 示例还提供 **Start (Rust)**。`workflowId` 留空时它会生成一个 Flow ID；后续调用把这个 ID 填作 `username`。

在 Dex Web 中打开这个 Flow 的 **Events**。**Timeline** 显示每次用户操作何时到达。**Graph** 显示每个已完成的 Step 以及它等待的 Timer 和 Channel。

[![Dex Web Timeline 展示注册、邮箱验证和两项入驻任务](https://docs.superdurable.io/img/use-cases/user-onboarding-process-timeline.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/user-onboarding-process-timeline.png)

[![Dex Web Graph 展示注册、邮箱验证和两项入驻任务](https://docs.superdurable.io/img/use-cases/user-onboarding-process-graph.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/user-onboarding-process-graph.png)

<a id="next"></a>

## 下一步

<a id="下一步"></a>

[转账](https://docs.superdurable.io/zh-Hans/examples/money-transfer.md)
