---
title: "职位发布"
description: "保存一条职位信息并支持搜索，同时把每个已接受的更新按顺序发送到 LinkedIn 和 Indeed。"
canonical_url: "https://docs.superdurable.io/zh-Hans/examples/job-posting/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/use-cases/job-post.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/job-posting.go.md) · [Java](https://docs.superdurable.io/zh-Hans/examples/job-posting.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/examples/job-posting.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/examples/job-posting.rust.md)

保存一条职位信息并支持搜索，同时把每个已接受的更新按顺序发送到 LinkedIn 和 Indeed。

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

**展示：**[实体 Flow](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow.md)、[等待 Attribute 匹配](https://docs.superdurable.io/zh-Hans/design-patterns/responsive-update/wait-for-attribute-match.md)。

**Flow 图：JobPostingFlow**

**Step 列表**

1. `InitStep`（起始 Step）：Start one posting update consumer for each job board. 下一步：`UpdateIndeedPosting`，或 `UpdateLinkedInPosting`。
2. `UpdateIndeedPosting`：Apply each queued posting update to Indeed in order. 下一步：`UpdateIndeedPosting`（再次）。 读取 `IndeedPostingUpdates`。
3. `UpdateLinkedInPosting`：Apply each queued posting update to LinkedIn in order. 下一步：`UpdateLinkedInPosting`（再次）。 读取 `LinkedInPostingUpdates`。

**RPC 列表**

- `get`
- `get_with_strong_consistency`
- `update`：读取 `UpdateVersion`；写入 `JobDescription`、`LastUpdateTimeMillis`、`Notes`、`Title`、`UpdateVersion`；锁定 `UpdatePostingLock`；发布到 `IndeedPostingUpdates`、`LinkedInPostingUpdates`。

例子: [examples/python/dex_examples/products/job-post/job_post_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/job-post/job_post_flow.py)

上图和本页描述覆盖 Python、Go、Java 和 TypeScript 示例。Go 示例把第一个 Step 命名为 `Init`。Rust 示例有几处名称不同，见 [Rust 示例](https://docs.superdurable.io/zh-Hans/examples/job-posting.md#rust-example)。

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

## 产品需求

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

每个 Flow 在整个生命周期内代表一条职位信息。它必须：

1. 保存职位名称、描述和备注。搜索按名称查找职位；描述只保存。
2. 一次接受一个替换后的职位信息，并给每个已接受的更新分配下一个版本号。
3. 立即返回这个版本，不等招聘网站。
4. 把每个已接受的更新按版本顺序发送到 LinkedIn 和 Indeed。每个招聘网站按自己的进度接收。
5. 每次招聘网站调用最多重试一小时：首次间隔 3 秒，最大间隔 60 秒，最多 100 次。
6. 删除职位时停止。

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

## Flow 设计

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

成功的那次 `InitStep` 为每个招聘网站启动一个 consumer Step。每个 consumer 在自己的 Channel 上等一条消息，发送这次更新，然后回到自身。

`update` RPC 声明对 `UpdatePostingLock` 的 lock。这个 Attribute 没有值。所以 Dex 一次只运行一个更新。每次更新递增 `UpdateVersion`，保存职位信息，并把同一个 `PostingUpdate` 发布到 `LinkedInPostingUpdates` 和 `IndeedPostingUpdates`。版本按 Dex 接受更新的先后排列，而不是按调用方发出请求的先后。

设计靠四个选择：

- [**实体 Flow**](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow.md)：Flow ID 就是这条职位，可检索的状态保存在 Attribute 中。`Title` 以 `text1` 建索引。
- **状态和消息一起保存**：Dex 把职位信息和两条 Channel 消息作为同一个 RPC 结果保存。已接受的更新总会同时排进两个招聘网站的队列。
- **消息自带快照**：每条消息都带着 RPC 当时看到的职位信息。consumer 从不读之后可能已改变的 Attribute。
- **FIFO consumer 循环**：consumer 处理完一条消息再回到自身。它重试期间，该招聘网站的后续消息都在等待，所以 v2 永远排在 v1 之后。

每个招聘网站只有一个 consumer，顺序由它的 Channel 保证。所以 consumer Step 不需要 lock。

每条消息都带幂等键 `<Flow ID>:<version>`。招聘网站调用可能已经成功但响应丢失，重试会再发一次同一个更新。招聘网站，或者它前面的适配器，必须按这个键丢弃重复请求。示例的桩服务只打印这条消息，其中包含这个键。没有哪个示例会向真实的招聘网站发送带键的请求。

每个 consumer 独立重试，所以慢的招聘网站只拖慢自己的更新。某个招聘网站用完重试后，Flow 失败，因为 consumer 没有失败路由。

删除会停止 Flow。仍在排队的更新不再发送，正在发送的那次仍可能完成。按产品的删除规则决定需要怎样处理。

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

## 核心实现

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

注意带 lock 的 `update` RPC 把同一个更新发布到两个 Channel，以及 consumer 循环。每个标签页都链接到对应的可运行示例。

**Python**

```python
UPDATE_VERSION = Attribute("UpdateVersion", int)
UPDATE_POSTING_LOCK = Attribute("UpdatePostingLock", type(None))
LINKEDIN_POSTING_UPDATES = Channel("LinkedInPostingUpdates", PostingUpdate)
INDEED_POSTING_UPDATES = Channel("IndeedPostingUpdates", PostingUpdate)


# dex:group group-id:setup group-label:"Setup"
# dex:explanation text:"Start one posting update consumer for each job board."
class InitStep(Step[None]):
    def execute(self, context: Context, input: None) -> StepDecision:
        return go_to_many(
            StepMovement.of(UpdateLinkedInPosting, None),
            StepMovement.of(UpdateIndeedPosting, None),
        )


# dex:group group-id:linkedin group-label:"LinkedIn"
# dex:explanation text:"Apply each queued posting update to LinkedIn in order."
class UpdateLinkedInPosting(Step[None]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_retry=JOB_BOARD_UPDATE_RETRY)

    def wait_for(self, context: Context, input: None) -> Wait:
        return Wait.until(LINKEDIN_POSTING_UPDATES.for_one())

    def execute(self, context: Context, input: None) -> StepDecision:
        update = LINKEDIN_POSTING_UPDATES.results(context)[0]
        self.service.update_external_system(
            f"update LinkedIn job posting v{update.version} "
            f"[{update.idempotency_key}]: {update.posting.title}"
        )
        return go_to(UpdateLinkedInPosting, None)


# dex:group group-id:indeed group-label:"Indeed"
# dex:explanation text:"Apply each queued posting update to Indeed in order."
class UpdateIndeedPosting(Step[None]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_retry=JOB_BOARD_UPDATE_RETRY)

    def wait_for(self, context: Context, input: None) -> Wait:
        return Wait.until(INDEED_POSTING_UPDATES.for_one())

    def execute(self, context: Context, input: None) -> StepDecision:
        update = INDEED_POSTING_UPDATES.results(context)[0]
        self.service.update_external_system(
            f"update Indeed job posting v{update.version} "
            f"[{update.idempotency_key}]: {update.posting.title}"
        )
        return go_to(UpdateIndeedPosting, None)


class JobPostingFlow(Flow[None]):
    # dex:indexed-attribute attribute-key:Title index-key:text1 index-type:fulltext value-type:string description:"Job posting title"
    title = Attribute("Title", str, AttributeIndex(IndexType.FULL_TEXT, "text1"))
    job_description = Attribute("JobDescription", str)
    # dex:indexed-attribute attribute-key:LastUpdateTimeMillis index-key:int1 index-type:int value-type:int64 description:"Last update time in milliseconds"
    last_update_time_millis = Attribute(
        "LastUpdateTimeMillis",
        int,
        AttributeIndex(IndexType.INT, "int1"),
    )
    notes = Attribute("Notes", str)
    update_version = UPDATE_VERSION
    update_posting_lock = UPDATE_POSTING_LOCK
    linkedin_posting_updates = LINKEDIN_POSTING_UPDATES
    indeed_posting_updates = INDEED_POSTING_UPDATES

    def __init__(self, service: MyDependencyService) -> None:
        self.service = service
        self.init = InitStep()
        self.update_linkedin_posting = UpdateLinkedInPosting(service)
        self.update_indeed_posting = UpdateIndeedPosting(service)

    def get_steps(self) -> StepList[None]:
        return StepList.start_step(self.init).other_steps(
            self.update_linkedin_posting,
            self.update_indeed_posting,
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(
            self.title,
            self.job_description,
            self.last_update_time_millis,
            self.notes,
            self.update_version,
            self.update_posting_lock,
            self.linkedin_posting_updates,
            self.indeed_posting_updates,
        )

    @rpc
    def get(self, context: Context) -> RPCResult[JobInfo]:
        return RPCResult(self.read_job_info(context))

    @rpc
    def get_with_strong_consistency(self, context: Context) -> RPCResult[JobInfo]:
        return self.get(context)

    @rpc(lock_attributes=(update_posting_lock.lock(),))
    def update(self, context: Context, input: JobInfo) -> RPCResult[int]:
        version = self.update_version.get(context) + 1
        self.title.set(context, input.title or "")
        self.job_description.set(context, input.description or "")
        self.last_update_time_millis.set(context, int(time.time() * 1000))
        if input.notes is not None:
            self.notes.set(context, input.notes)
        self.update_version.set(context, version)
        update = PostingUpdate(
            version,
            f"{context.flow_id}:{version}",
            input,
        )
        self.linkedin_posting_updates.publish(context, update)
        self.indeed_posting_updates.publish(context, update)
        return RPCResult(version)
```

例子: [examples/python/dex_examples/products/job-post/job_post_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/job-post/job_post_flow.py)

<a id="rust-example"></a>

## Rust 示例

Rust 示例把第一个 Step 命名为 `Init`。`Init` 把启动输入保存为职位信息。整条职位信息保存在 `job-post` Attribute 中，名称保存在 `job-post-title` 中，并以 `text1` 建索引。Rust 还注册了 `DeleteJobPost` RPC：它把职位标记为已删除，Flow 继续运行，之后的更新会失败。下面的 playground 调用对 Rust 同样适用。

<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)启动一种语言的示例。在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 中选择 **Job posting**。**Create** 创建一条职位并返回它的 Flow ID；其他调用把它填作 `workflowId`。运行两次 **Update**。**Read** 返回最新的职位信息。**Search** 用查询 `text1 = 'Staff'` 找到名称含这个词的职位。等 Dex Web 显示每个招聘网站都已完成两次执行，再运行 **Delete / stop** 停止 Flow。示例还提供 `/products/job-post/wait-for-update`，它会等到 `UpdateVersion` 超过给定的 `lastRevision`。

在 Dex Web 中打开 **Events**。**Timeline** 按顺序显示两次更新。**Graph** 显示每个招聘网站的两次执行，以及运行停止时被取消的等待中的 consumer。

[![Dex Web Timeline 展示两次职位发布更新](https://docs.superdurable.io/img/use-cases/job-post-timeline.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/job-post-timeline.png)

[![Dex Web Graph 展示两次职位发布更新](https://docs.superdurable.io/img/use-cases/job-post-graph.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/job-post-graph.png)

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

## 下一步

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

- [客户退款](https://docs.superdurable.io/zh-Hans/examples/customer-refund.md)
- [实体 Flow](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow.md)
- [静态并行 Step](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/static-parallel-steps.md)
- [Channel](https://docs.superdurable.io/zh-Hans/concepts/primitives/channel.md)
- [RPC](https://docs.superdurable.io/zh-Hans/concepts/primitives/rpc.md)
- [Attribute](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md)
- [Client APIs](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md)（英文）
