---
title: "带结论的空闲定时器"
description: "记录每一条到达的消息，在有人给出结论或一段时间内没有新消息时结束（以前叫作入站事件循环，Inbound Event Loop）。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/idle-timer-with-resolution/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/external-interaction/idle-timer-with-resolution.mdx"
locale: "zh-Hans"
language: "python"
---

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

# 带结论的空闲定时器

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

记录每一条到达的消息，在有人给出结论或一段时间内没有新消息时结束（以前叫作入站事件循环，Inbound Event Loop）。

当 Flow 需要持续接收外部消息，直到收到结论或对话长时间没有动静时，使用这个模式。例如工单里的回复、聊天会话里的消息，或评审讨论里的答复。它是 [空闲定时器](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/idle-timer.md) 的扩展：每条消息都会让不活跃 Timer 重新计时，另一个表示结论的消息会结束循环。

**Flow 图：SupportTicketConversationFlow**

**Step 列表**

1. `AwaitTicketMessage`（起始 Step）：Record each batch of replies, or route on the resolution or the inactivity Timer. 下一步：`CloseResolvedTicket`、`AwaitTicketMessage`（再次），或 `CloseInactiveTicket`。 读取 `transcriptChunks`、`ticketReplies`、`ticketResolutions`；写入 `transcriptChunks`。
2. `CloseInactiveTicket`：Close the quiet ticket once no reply or resolution is waiting. 下一步：`AwaitTicketMessage`。
3. `CloseResolvedTicket`：Close the resolved ticket once no reply is left to record. 下一步：`AwaitTicketMessage`。

**RPC 列表**

- `resolve_ticket`：发布到 `ticketResolutions`。
- `send_ticket_reply`：发布到 `ticketReplies`。

例子: [examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py)

<a id="how-it-works"></a>

## 工作方式

1. 一个 RPC 校验每条回复，然后把它发布到回复 Channel。另一个 RPC 校验结论，然后把它发布到结论 Channel。
2. 一个等待中的 Step 返回 `AnyOf`，等待回复 Channel、结论 Channel 和不活跃 Timer。
3. 回复胜出时，它的 `Execute` 把回复追加到 transcript，然后回到同一个 Step。新的执行会注册新的等待，所以不活跃 Timer 重新开始计时。
4. 结论胜出时，`Execute` 进入关闭已解决工单的 Step。Timer 胜出时，进入关闭长时间没有动静的工单的 Step。
5. 每个结束 Step 都用 `ForceCompleteIfChannelsEmpty` 结束 Flow。关闭决策检查这个 Step 指定的 Channel，并在同一次原子提交里接受关闭。在这次检查之前已提交、并且仍在受检 Channel 里的消息，会让 Dex 回到等待中的 Step，而不是关闭 Flow。

<a id="rules"></a>

## 规则

- RPC 只校验输入，然后把它发布到 Channel。它不写入等待中的 Step 会读取或加锁的 Attribute。
- 只有一个等待中的 Step。它用 `AnyOf` 等待回复 Channel、结论 Channel 和不活跃 Timer。
- 先声明回复 Channel，再声明结论 Channel。多个 Channel Condition 同时就绪时，先声明的那个胜出，并且只消费胜出者的消息。所以在结论之前收到的回复总会先被记录。
- Channel Condition 只有胜出时才消费消息。`Execute` 运行期间到达的回复会留在队列里，由下一次执行处理，不会丢失。
- `Execute` 把消费到的消息追加到一个 Attribute，例如 transcript。等待中的 Step 是这个 Attribute 唯一的写入者。
- 然后 `Execute` 回到同一个 Step。新的执行会注册新的等待，所以每条消息之后不活跃 Timer 都会重新开始。
- 要一次取走所有排队的回复，用“至少一条”的 Channel Condition。也可以每次执行只取一条。
- 让 transcript 保持有界。长对话把消息存放在 [sequentially chunked AttributeMap](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/sequentially-chunked-attribute-map.md) 中。示例中等待中的 Step 只加载当前分块。

<a id="why-the-rpc-does-not-write-the-transcript"></a>

## 为什么由 Step 负责 transcript

如果由 RPC 追加 transcript，等待中的 Step 就必须锁住 transcript，RPC 为了读取再修改也必须加锁。锁不会排队。只要 Step 或另一个 RPC 持有这把锁，新到的 RPC 都会因为锁冲突被拒绝，客户端只能重试。发布到 Channel 不需要锁，所以并发的回复不会冲突。

<a id="messages-at-the-close"></a>

## 关闭时到达的消息

每个结束 Step 都在回复 Channel 上用 `ForceCompleteIfChannelsEmpty` 结束 Flow，做法见 [排空外部 Channel](https://docs.superdurable.io/zh-Hans/design-patterns/draining-channel-for-external-publishing.md)。它的 fallback 回到等待中的 Step。

- 只有原子检查时回复 Channel 为空，结论才会关闭 Flow。在这次检查之前已提交、仍在排队或已被领取但 Step 还没完成的回复会触发 fallback，fallback 带着结论回到等待中的 Step。这个 Step 只等待回复，把它们写入 transcript，然后再次进入结论关闭。
- 因不活跃而关闭时，还要检查结论 Channel。回复或结论可能在 Timer 胜出之后、不活跃关闭运行之前提交。它的检查发现这条消息，fallback 重新开始等待。之后回复会写入 transcript，结论会进入结论关闭。
- 回复 Channel 只能由等待中的 Step 消费。

结论 RPC 拒绝空的原因，因为空的待定结论表示“没有结论”。

在检查之后、关闭仍在进行时发布消息的 RPC 会因 `FLOW_CLOSING` 失败，不提交任何内容；见 [Pending close](https://docs.superdurable.io/zh-Hans/reference/server/runtime-client.md#pending-close)（英文）。Flow 关闭期间到达的请求，处理方式见 [Requests during Flow close](https://docs.superdurable.io/zh-Hans/reference/server/runtime-client.md#requests-during-flow-close)（英文）。

RPC 成功只确认消息已经发布。确认消息已被处理是另一件事。调用方必须确认每条回复都已处理时，等待中的 Step 在同一次提交里记录回复的业务 ID，调用方读取这份记录。重试同一次投递时，沿用它的 RPC request ID。重新投递一条回复之前，先在这份记录里检查它的业务 ID。见 [确认消息已处理](https://docs.superdurable.io/zh-Hans/reference/server/runtime-client.md#confirm-message-handled)（英文）。

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

## 示例

`SupportTicketConversationFlow` 接收支持工单的回复。`sendTicketReply` 拒绝空回复和过长的回复。`resolveTicket` 拒绝空的原因。`AwaitTicketMessage` 记录回复，或者进入 `CloseResolvedTicket` 或 `CloseInactiveTicket`。它的输入是待定结论；只有结论关闭走了 fallback 时，这个输入才不为空。不活跃 Timer 是 24 小时。测试用 Client 的 `SkipTimer` 跳过它，而不是缩短时间。

**Python**

```python
TICKET_REPLIES = Channel("ticketReplies", str)
TICKET_RESOLUTIONS = Channel("ticketResolutions", str)
TRANSCRIPT_CHUNKS = AttributeMap("transcriptChunks", TranscriptChunk)


class AwaitTicketMessage(Step[str]):
    """Waits for replies, a resolution, or inactivity; the input is a pending resolution."""

    def wait_for(self, context: Context, pending_resolution: str) -> Wait:
        if pending_resolution:
            return Wait.until(TICKET_REPLIES.at_least(1))
        # Replies come before the resolution, so earlier replies are recorded first.
        return Wait.any_of(
            TICKET_REPLIES.at_least(1),
            TICKET_RESOLUTIONS.for_one(),
            Timer.by_duration(INACTIVITY_TIMEOUT),
        )

    def execute(self, context: Context, pending_resolution: str) -> StepDecision:
        replies = TICKET_REPLIES.results(context)
        if replies:
            # Appends replies to the current chunk and archives each full chunk.
            chunk = TRANSCRIPT_CHUNKS.get(context, CURRENT_TRANSCRIPT_CHUNK) or TranscriptChunk()
            next_sequence = chunk.replies[-1].sequence + 1 if chunk.replies else 1
            for text in replies:
                if len(chunk.replies) == TRANSCRIPT_CHUNK_SIZE:
                    archive_token = archive_chunk_token(chunk.replies[0].sequence)
                    TRANSCRIPT_CHUNKS.set(context, archive_token, chunk)
                    chunk = TranscriptChunk()
                chunk.replies.append(TicketReply(next_sequence, text))
                next_sequence += 1
            TRANSCRIPT_CHUNKS.set(context, CURRENT_TRANSCRIPT_CHUNK, chunk)
            if pending_resolution:
                return go_to(CloseResolvedTicket, pending_resolution)
            # A new execution registers a new wait, so the Timer restarts.
            return go_to(AwaitTicketMessage, "")
        resolutions = TICKET_RESOLUTIONS.results(context)
        if resolutions:
            return go_to(CloseResolvedTicket, resolutions[0])
        if context.has_timer_fired():
            return go_to(CloseInactiveTicket, None)
        raise RuntimeError("no Condition of the ticket wait completed")

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_load_attribute_map_instances=(
                TRANSCRIPT_CHUNKS.load(CURRENT_TRANSCRIPT_CHUNK),
            )
        )


class CloseResolvedTicket(Step[str]):
    def execute(self, context: Context, reason: str) -> StepDecision:
        return force_complete_if_channels_empty(
            f"resolved: {reason}",
            StepMovement.of(AwaitTicketMessage, reason),
            TICKET_REPLIES,
        )


class CloseInactiveTicket(Step[None]):
    def execute(self, context: Context, input: None) -> StepDecision:
        return force_complete_if_channels_empty(
            "closed after inactivity",
            StepMovement.of(AwaitTicketMessage, ""),
            TICKET_REPLIES,
            TICKET_RESOLUTIONS,
        )


class SupportTicketConversationFlow(Flow[str]):
    @rpc
    def send_ticket_reply(self, context: Context, text: str) -> None:
        """Validates one reply and queues it for the waiting Step."""
        if not text.strip():
            raise ValueError("reply text is required")
        if len(text) > MAX_REPLY_LENGTH:
            raise ValueError(f"reply text exceeds {MAX_REPLY_LENGTH} characters")
        TICKET_REPLIES.publish(context, text)

    @rpc
    def resolve_ticket(self, context: Context, reason: str) -> None:
        """Queues the resolution; an empty reason would mean no resolution."""
        if not reason.strip():
            raise ValueError("resolution reason is required")
        TICKET_RESOLUTIONS.publish(context, reason)
```

例子: [examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py)

transcript 更新逻辑、HTTP controller 和测试都在示例目录里。可以在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 里运行这个 HTTP 示例。

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

## 下一步

- [控制长时间运行的工作](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/control-long-running-work.md)
- [Channel](https://docs.superdurable.io/zh-Hans/concepts/primitives/channel.md)
- [Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md)
- [RPC](https://docs.superdurable.io/zh-Hans/concepts/primitives/rpc.md)
- [排空 Channel](https://docs.superdurable.io/zh-Hans/design-patterns/drain-channels.md)
