---
title: "回应窗口"
description: "回应窗口告诉每个得到业务结果的调用方，它的回应是否起了决定作用。当调用方必须知道自己的回应是否赶上了截止时间时，把它加到带截止时间的决定上，例如客户恰好在报价过期时接受报价。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/response-window/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/external-interaction/response-window.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/response-window.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/response-window.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/response-window.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/response-window.rust.md)

回应窗口告诉每个得到业务结果的调用方，它的回应是否起了决定作用。当调用方必须知道自己的回应是否赶上了截止时间时，把它加到[带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md)上，例如客户恰好在报价过期时接受报价。

**Flow 图：OfferResponseFlow**

**Step 列表**

1. `AwaitOfferResponse`（起始 Step）：Waits for an acceptance, a rejection, or the 3-day deadline, closes the response window, and routes on the winner. 下一步：`RouteResponseBeforeExpiry`、`ExpireOffer`、`FulfillOffer`，或 `CloseRejectedOffer`。 读取 `offerAccepted`、`offerRejected`；锁定 `offerResponseWindow`；写入 `offerResponseWindow`。
2. `CloseRejectedOffer`：Completes the Flow with the rejected offer. 下一步：Flow 完成。
3. `ExpireOffer`：Completes the Flow with the expired offer. 下一步：Flow 完成。
4. `FulfillOffer`：Completes the Flow with the fulfilled offer. 下一步：Flow 完成。
5. `RouteResponseBeforeExpiry`：Takes the response that the customer sent before the window closed and routes on it. 下一步：`FulfillOffer`，或 `CloseRejectedOffer`。 读取 `offerAccepted`。

**RPC 列表**

- `accept_customer_offer`：锁定 `offerResponseWindow`。
- `reject_customer_offer`：锁定 `offerResponseWindow`。

例子: [examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py)

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

## 工作方式

如果业务可以接受截止时间刚过才到的回应被忽略，就不需要窗口：回应 RPC 只发布消息，不加锁。否则调用方可能被告知回应已记录，但这个回应并没有起决定作用。这有两种情况：

- 回应在 Timer 胜出之后、`Execute` 运行之前提交。它的 RPC 返回成功，随后 `Execute` 让报价过期，忽略了这个回应。
- 接受和拒绝都在等待取走其中一个之前提交。两个 RPC 都返回成功，但等待只消费其中一个。

只在 `Execute` 里读取 Channel 大小会留下这些缺口，因为读取之后仍可能有回应提交。`ForceCompleteIfChannelsEmpty` 可以在关闭 Flow 之前路由一条排队中的回应。只能接纳一个回应时，使用回应窗口。

示例用 Attribute 锁堵住这些缺口：

1. `offerResponseWindow` Attribute 初始为打开：未设置的值视为打开。
2. 两个回应 RPC 都锁住 `offerResponseWindow`。带锁的 RPC 是事务性的，所以它的检查、发布和窗口写入一起提交。第一个回应发布消息、关闭窗口，并返回“已记录”。Flow 仍活跃时，之后的回应不发布任何消息，返回“窗口已关闭”。任何时候最多只有一个回应在排队。
3. `AwaitOfferResponse` 的 `Execute` 锁住同一个 Attribute，并在每个分支上关闭窗口。Dex 先拿到锁，再把 `Execute` 交给 Worker，之后才读取状态。
4. Timer 胜出时，在拿锁之前提交的回应已经在它的 Channel 里。`Execute` 通过 Channel 大小看到它，进入 `RouteResponseBeforeExpiry`，这个 Step 的等待会立刻取走这条回应。

这是一个软截止。截止点是加锁的 `Execute` 拿到锁的那一刻，而不是 Timer 触发的那一刻。在这之间提交的第一个回应会被接受，并决定这份报价。这个 `Execute` 提交后，窗口保持关闭。之后的回应先等锁，拿到锁时窗口已经关闭。handler 正常返回时给出的每个业务结果都是真实的。

<a id="hard-cutoff"></a>

### 严格截止

如果业务要求严格截止，就在等待开始之前把截止时间保存在 Flow 中。在窗口锁下，当[可信的收件时间](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#decision-windows-and-rounds)（英文）达到或超过截止时间时，回应 RPC 返回“窗口已关闭”。如果 Timer 胜出，Channel 大小检查仍会取走已经接纳到 Channel 里的那一个回应。

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

## 规则

- 每个写回应 Channel 的 RPC 都声明同一把锁。每个回应 Channel 最好只有一个入口 RPC。
- 每个能做出决定的 RPC 都检查并关闭同一个窗口。
- 只锁 `Execute`。`WaitFor` 不加锁。
- 加锁的 `Execute` 设置窗口、检查胜出者和 Channel 大小，然后路由。外部调用放到下一个 Step，因为回应 RPC 在等这把锁。
- 给加锁的 `Execute` 设一个短的重试预算。失败的 `Execute` 在重试期间一直持有锁，等待中的回应可能因此达到等锁上限。参见 [Lock holding](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#lock-holding)（英文）。
- 调用方遇到锁冲突时，用有上限的退避重试，重试用完时得到错误。让每个回应都是幂等的，例如使用业务回应 ID。参见 [Decision windows and rounds](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#decision-windows-and-rounds)（英文）。
- 回应 RPC 也可以在锁下把被接纳的回应记录为结果。`Execute` 仍然检查是哪个 Condition 触发了，并且只从 Timer 结果得知 Timer 是否触发。
- 只有 handler 正常返回的调用才得到业务结果。Flow 关闭后，Dex 在 handler 运行之前就拒绝这个 RPC。示例的 HTTP 路由把仍在保留期内的已关闭 Flow 映射为 `409`，把找不到的 Flow 映射为 `404`。
- 要再次等待时，在开始下一轮等待的 `Execute` 里，在同一把锁下重新打开窗口。
- 窗口关闭后仍在排队的回应会留在它的 Channel 里，下一次等待这个 Channel 时会消费它。再次等待之前，删除它，或者按轮次给回应设键。

<a id="test"></a>

## 测试

覆盖这些场景：

- 截止时间之前的回应做出决定。
- 紧接着发送的两个回应，一个得到“已记录”，一个得到“窗口已关闭”。
- Flow 仍活跃、窗口已关闭时到达的回应得到“窗口已关闭”。
- 在 Timer 胜出之后、加锁的 `Execute` 运行之前提交的回应，通过 Channel 大小检查被取走。
- 使用严格截止时，达到或超过已保存截止时间的回应得到“窗口已关闭”。

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

## 核心实现

示例就是[带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md)的示例。这段摘录展示窗口部分：回应 RPC、窗口检查和做决定的 `Execute` 的锁。HTTP 路由（包括 lock conflict 重试和已关闭 Flow 的检查）在示例目录里。可以在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 里试用这些路由。

**Python**

```python
# The first response or AwaitOfferResponse closes the response window. Unset reads as open.
RESPONSE_WINDOW_OPEN = "open"
RESPONSE_WINDOW_CLOSED = "closed"

# The outcomes of a customer response RPC.
OFFER_RESPONSE_RECORDED = "recorded"
OFFER_RESPONSE_WINDOW_CLOSED = "window closed"

# Locked by both response RPCs and by AwaitOfferResponse.execute.
OFFER_RESPONSE_WINDOW = Attribute("offerResponseWindow", str)

# A short retry budget for the execute that holds the window lock.
WINDOW_CLOSE_RETRY = RetryPolicy(
    initial_interval=timedelta(seconds=1),
    maximum_attempts=3,
    total_duration=timedelta(minutes=1),
)
WINDOW_CLOSE_ATTEMPT_TIMEOUT = timedelta(seconds=10)


def read_response_window(context: Context) -> str:
    """Returns RESPONSE_WINDOW_OPEN while the window was never closed."""
    return OFFER_RESPONSE_WINDOW.get(context) or RESPONSE_WINDOW_OPEN


def publish_while_window_open(
    context: Context, response: Channel[str], note: str
) -> RPCResult[str]:
    """Publishes the first response and closes the window; later responses get window closed.

    The check, the publish, and the close commit together, because the RPC holds the window lock.
    """
    if read_response_window(context) == RESPONSE_WINDOW_CLOSED:
        return RPCResult(OFFER_RESPONSE_WINDOW_CLOSED)
    response.publish(context, note)
    # The first reply closes the window, so a second reply cannot also be recorded.
    OFFER_RESPONSE_WINDOW.set(context, RESPONSE_WINDOW_CLOSED)
    return RPCResult(OFFER_RESPONSE_RECORDED)


class AwaitOfferResponse(Step[str]):
    def get_step_options(self) -> StepOptions:
        """Locks the response window in execute, the same lock as the response RPCs."""
        return StepOptions(
            execute_lock_attributes=(OFFER_RESPONSE_WINDOW.lock(),),
            # Responses get lock conflicts while this execute retries, so keep the budget short.
            execute_retry=WINDOW_CLOSE_RETRY,
            execute_method_timeout=WINDOW_CLOSE_ATTEMPT_TIMEOUT,
        )


class OfferResponseFlow(Flow[str]):
    @rpc(lock_attributes=(OFFER_RESPONSE_WINDOW.lock(),))
    def accept_customer_offer(self, context: Context, note: str) -> RPCResult[str]:
        """Records that the customer accepted the offer.

        Returns OFFER_RESPONSE_WINDOW_CLOSED once a response was recorded or the offer decided.
        """
        return publish_while_window_open(context, OFFER_ACCEPTED, note)
```

例子: [examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py)

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

## 下一步

- [加锁决定轮次](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/locked-decision-rounds.md)
- [带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md)
- [Attribute locks](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#attribute-locks)（英文）
