回应窗口
查看 Markdown回应窗口告诉每个得到业务结果的调用方,它的回应是否起了决定作用。当调用方必须知道自己的回应是否赶上了截止时间时,把它加到带截止时间的决定上,例如客户恰好在报价过期时接受报价。
工作方式
如果业务可以接受截止时间刚过才到的回应被忽略,就不需要窗口:回应 RPC 只发布消息,不加锁。否则调用方可能被告知回应已记录,但这个回应并没有起决定作用。这有两种情况:
- 回应在 Timer 胜出之后、
Execute运行之前提交。它的 RPC 返回成功,随后Execute让报价过期,忽略了这个回应。 - 接受和拒绝都在等待取走其中一个之前提交。两个 RPC 都返回成功,但等待只消费其中一个。
只在 Execute 里读取 Channel 大小会留下这些缺口,因为读取之后仍可能有回应提交。ForceCompleteIfChannelsEmpty 可以在关闭 Flow 之前路由一条排队中的回应。只能接纳一个回应时,使用回应窗口。
示例用 Attribute 锁堵住这些缺口:
offerResponseWindowAttribute 初始为打开:未设置的值视为打开。- 两个回应 RPC 都锁住
offerResponseWindow。带锁的 RPC 是事务性的,所以它的检查、发布和窗口写入一起提交。第一个回应发布消息、关闭窗口,并返回“已记录”。Flow 仍活跃时,之后的回应不发布任何消息,返回“窗口已关闭”。任何时候最多只有一个回应在排队。 AwaitOfferResponse的Execute锁住同一个 Attribute,并在每个分支上关闭窗口。Dex 先拿到锁,再把Execute交给 Worker,之后才读取状态。- Timer 胜出时,在拿锁之前提交的回应已经在它的 Channel 里。
Execute通过 Channel 大小看到它,进入RouteResponseBeforeExpiry,这个 Step 的等待会立刻取走这条回应。
这是一个软截止。截止点是加锁的 Execute 拿到锁的那一刻,而不是 Timer 触发的那一刻。在这之间提交的第一个回应会被接受,并决定这份报价。这个 Execute 提交后,窗口保持关闭。之后的回应先等锁,拿到锁时窗口已经关闭。handler 正常返回时给出的每个业务结果都是真实的。
严格截止
如果业务要求严格截止,就在等待开始之前把截止时间保存在 Flow 中。在窗口锁下,当可信的收件时间(英文)达到或超过截止时间时,回应 RPC 返回“窗口已关闭”。如果 Timer 胜出,Channel 大小检查仍会取走已经接纳到 Channel 里的那一个回应。
规则
- 每个写回应 Channel 的 RPC 都声明同一把锁。每个回应 Channel 最好只有一个入口 RPC。
- 每个能做出决定的 RPC 都检查并关闭同一个窗口。
- 只锁
Execute。WaitFor不加锁。 - 加锁的
Execute设置窗口、检查胜出者和 Channel 大小,然后路由。外部调用放到下一个 Step,因为回应 RPC 在等这把锁。 - 给加锁的
Execute设一个短的重试预算。失败的Execute在重试期间一直持有锁,等待中的回应可能因此达到等锁上限。参见 Lock holding(英文)。 - 调用方遇到锁冲突时,用有上限的退避重试,重试用完时得到错误。让每个回应都是幂等的,例如使用业务回应 ID。参见 Decision windows and rounds(英文)。
- 回应 RPC 也可以在锁下把被接纳的回应记录为结果。
Execute仍然检查是哪个 Condition 触发了,并且只从 Timer 结果得知 Timer 是否触发。 - 只有 handler 正常返回的调用才得到业务结果。Flow 关闭后,Dex 在 handler 运行之前就拒绝这个 RPC。示例的 HTTP 路由把仍在保留期内的已关闭 Flow 映射为
409,把找不到的 Flow 映射为404。 - 要再次等待时,在开始下一轮等待的
Execute里,在同一把锁下重新打开窗口。 - 窗口关闭后仍在排队的回应会留在它的 Channel 里,下一次等待这个 Channel 时会消费它。再次等待之前,删除它,或者按轮次给回应设键。
测试
覆盖这些场景:
- 截止时间之前的回应做出决定。
- 紧接着发送的两个回应,一个得到“已记录”,一个得到“窗口已关闭”。
- Flow 仍活跃、窗口已关闭时到达的回应得到“窗口已关闭”。
- 在 Timer 胜出之后、加锁的
Execute运行之前提交的回应,通过 Channel 大小检查被取走。 - 使用严格截止时,达到或超过已保存截止时间的回应得到“窗口已关闭”。
核心实现
示例就是带截止时间的决定的示例。这段摘录展示窗口部分:回应 RPC、窗口检查和做决定的 Execute 的锁。HTTP 路由(包括 lock conflict 重试和已关闭 Flow 的检查)在示例目录里。可以在 examples playground 里试用这些路由。
# 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.
例子: examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py
// The response window is open until the first reply or AwaitOfferResponse closes it. Unset reads as open.
const (
ResponseWindowOpen = "open"
ResponseWindowClosed = "closed"
)
// The outcomes of a customer response RPC.
const (
OfferResponseRecorded = "recorded"
OfferResponseWindowClosed = "window closed"
)
// OfferResponseWindow is locked by both response RPCs and by AwaitOfferResponse.Execute.
OfferResponseWindow = dex.DefineAttribute[string]("offerResponseWindow")
var responseWindowLock = []dex.AttributeLock{dex.LockAttribute(OfferResponseWindow)}
// A failing locked Execute holds the window lock through its retries, so keep the budget short.
const (
awaitOfferResponseRetryInterval = time.Second
awaitOfferResponseMaxAttempts = 3
awaitOfferResponseRetryBudget = time.Minute
awaitOfferResponseMethodTimeout = 10 * time.Second
)
func (flow *OfferResponseFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.AcceptCustomerOffer, &dex.RPCOptions{LockAttributes: responseWindowLock}),
dex.DefineRPC(flow.RejectCustomerOffer, &dex.RPCOptions{LockAttributes: responseWindowLock}),
dex.DefineRPC(flow.GetDexSummary, nil),
// The locked execute holds the window lock through its retries, so keep the budget short.
private static final RetryPolicy WINDOW_EXECUTE_RETRY = RetryPolicy.newBuilder()
.initialInterval(Duration.ofSeconds(1))
.maximumAttempts(3)
.totalDuration(Duration.ofMinutes(1))
.build();
private static final Duration WINDOW_EXECUTE_TIMEOUT = Duration.ofSeconds(10);
/** The first response or AwaitOfferResponse closes the window. Unset reads as open. */
public static final String RESPONSE_WINDOW_OPEN = "open";
public static final String RESPONSE_WINDOW_CLOSED = "closed";
/** The outcomes of a customer response RPC. */
public static final String OFFER_RESPONSE_RECORDED = "recorded";
public static final String OFFER_RESPONSE_WINDOW_CLOSED = "window closed";
/** Locked by both response RPCs and by AwaitOfferResponse's execute. */
public static final Attribute<String> offerResponseWindow =
Attribute.define("offerResponseWindow", String.class);
/**
* Records that the customer accepted the offer.
*
* @return {@link #OFFER_RESPONSE_WINDOW_CLOSED} after the first response or the decision
*/
@RPC(lockAttributes = {"offerResponseWindow"})
public RPCResult<String> acceptCustomerOffer(final Context context, final String note) {
return publishWhileWindowOpen(context, offerAccepted, note);
}
例子: examples/java/src/main/java/io/superdurable/dex/patterns/deferredchoice/OfferResponseFlow.java
/** The first reply or AwaitOfferResponse closes the response window. Unset reads as open. */
export const RESPONSE_WINDOW_OPEN = "open";
export const RESPONSE_WINDOW_CLOSED = "closed";
/** The outcomes of a customer response RPC. */
export const OFFER_RESPONSE_RECORDED = "recorded";
export const OFFER_RESPONSE_WINDOW_CLOSED = "window closed";
/** Locked by both response RPCs and by AwaitOfferResponse.execute. */
export const offerResponseWindow = new Attribute(
"offerResponseWindow",
stringCodec,
);
/** Responses get lock conflicts while the locked execute retries, so its retry budget stays short. */
export const AWAIT_OFFER_RESPONSE_EXECUTE_RETRY: RetryPolicy = {
initialIntervalMs: 1000,
maximumAttempts: 3,
totalDurationMs: 60 * 1000,
};
export const AWAIT_OFFER_RESPONSE_EXECUTE_TIMEOUT_MS = 10 * 1000;
/**
* Publishes the first response and closes the window. The RPC lock commits both with the check.
*/
export function publishWhileWindowOpen(
context: Context,
response: Channel<string>,
note: string,
): RPCResult<string> {
例子: examples/typescript/src/patterns/deferred-choice/offer-response-flow.ts
/// The response window is open until the first reply or `AwaitOfferResponse` closes it. Unset reads as open.
pub const RESPONSE_WINDOW_OPEN: &str = "open";
pub const RESPONSE_WINDOW_CLOSED: &str = "closed";
/// The retry budget of the locked `AwaitOfferResponse` Execute.
pub const DECIDE_RETRY_INITIAL_INTERVAL: Duration = Duration::from_secs(1);
pub const DECIDE_RETRY_MAXIMUM_ATTEMPTS: u32 = 3;
pub const DECIDE_RETRY_TOTAL_DURATION: Duration = Duration::from_secs(60);
pub const DECIDE_EXECUTE_TIMEOUT: Duration = Duration::from_secs(10);
/// The outcomes of a customer response RPC.
pub const OFFER_RESPONSE_RECORDED: &str = "recorded";
pub const OFFER_RESPONSE_WINDOW_CLOSED: &str = "window closed";
/// Locked by both response RPCs and by `AwaitOfferResponse::execute`.
pub static OFFER_RESPONSE_WINDOW: LazyLock<Attribute<String>> =
LazyLock::new(|| Attribute::new("offerResponseWindow"));
/// Publishes the first response and closes the window; later responses get the closed result.
/// The check, the publish, and the close commit together, because the RPC holds the window lock.
fn publish_while_window_open(
context: &mut Context,
response: &Channel<String>,
note: String,
) -> HandlerResult<RpcResult<String>> {
let window = OFFER_RESPONSE_WINDOW.get(context)?;
if window.as_deref() == Some(RESPONSE_WINDOW_CLOSED) {
return Ok(RpcResult::new(OFFER_RESPONSE_WINDOW_CLOSED.to_string()));
}
response.publish(context, note)?;
例子: examples/rust/src/control_patterns/deferred_choice/flow.rs