临界区
查看 Markdown当同一个 Flow 的多个并行分支必须轮流执行一段由多个 Step 组成的流程时,使用 Critical Section。同一时刻只能有一个分支处在这段流程中。
例如多位审核人编辑同一份合同。每次编辑需要三个 Step:第一个拿到编辑权,第二个修改合同,第三个保存并把编辑权交给下一位。两次编辑绝不能交错。
工作方式
一个专用 Channel 里恰好只有一条消息,这条消息就是 token。
- 在任何分支进入之前,由一个 Step 发布一次 token。
- 一个交接 Step 用
ForOne等待 token。一条消息只满足一个等待,所以只有一个分支能拿到它,其余分支继续等待。 - 交接 Step 不做任何受保护的工作。它的
Execute只转到第一个做受保护工作的 Step。 - 这段流程的最后一个 Step 把 token 发布回去。某个正在等待的分支消费它并进入。
在示例中:
StartContractEdits先把 token 放进 Channel,再为每份修改启动一个分支,同时启动FinishContractEdits,由它等待所有修改结束。- 每个分支在
EnterContractEdit中等待 token,拿到后才进入。 EditContract修改合同后进入SaveContractEdit,由它记录已保存的修改并把 token 放回去。审阅人撤回时,EditContract改为记录撤回并把 token 放回去。EnterContractEdit、EditContract或SaveContractEdit的Execute重试耗尽时,ExecuteFailure把它路由到ReleaseContractEditToken。这个 Step 记录失败的修改并把 token 放回去。
任何等待中的分支都可能下一个拿到 token,顺序不固定。
Token 还是 Attribute lock
Attribute lock(例如 ExecuteLockAttributes)只覆盖一个 Step 方法。它不覆盖 WaitFor,也不能跨越多个 Step。受保护的工作能放进一次 Execute 时,用 lock。这段流程跨越多个 Step 时,用 token。
每个出口都要归还 token
token 只是一条普通消息。如果某个分支离开这段流程时没有把它发布回去,其他所有分支会永远等待。列出离开这段流程的每一种方式,并在每一种方式上发布 token。
- 正常退出。 这段流程的最后一个 Step 发布 token。
- Execute 失败。 用
ExecuteFailure把失败路由到一个发布 token 的 Step。这段流程的每个 Step 都要配置这条路由。在示例中,EnterContractEdit、EditContract和SaveContractEdit都会进入ReleaseContractEditToken。 - WaitFor 失败。 如果这段流程中后面的某个 Step 有自己的
WaitFor,给它配置继续执行Execute的WaitForFailure策略。那个Execute看到失败后发布 token。 - 提前退出。 用业务决定提前离开这段流程的
Execute,要在同一个Execute中发布 token。 - 交接 Step 被取消。 取消交接 Step 是安全的,因为它不做受保护的工作。如果取消发生在它的等待已经消费 token、而 Dex 还没保存它的
Execute结果时,Dex 会把 token 放回 Channel 的最前面,另一个分支随后进入。 - 在段内被取消。 绝不要取消做受保护工作的 Step。被取消的 Step 不会发布 token;见取消一个会发布消息的 Step。要提前停止一个分支,给它发送一个它会检查的停止请求,例如由 RPC 设置的 Attribute。看到请求的 Step 通过发布 token 的提前退出离开这段流程。
- 关闭 Flow。
ForceComplete、ForceFail、Flow timeout 和 Client 的StopFlow会结束所有分支,不再有分支等待 token。
Dex 把一个方法的 Channel 发布和它的结果一起保存,要么都保存,要么都不保存。失败的尝试不会发布任何消息,所以重试不会产生第二个 token。
Dex 归还 token 之后,被取消的 Execute 仍可能继续运行,并写入外部系统。这是绝不要取消做受保护工作的 Step 的另一个原因。
规则
- 只发布一个 token,在启动各分支的 Step 中发布,或者更早。多一个 token,就会有两个分支同时进入这段流程。
- token Channel 只用于 token。
- 让这段流程尽量短。一个分支在段内时,其余分支都在等待。
- token 的值无关紧要。受保护的状态放在 Attribute 中。
示例
ContractEditFlow 以一组编辑请求启动,每位审核人一个。StartContractEdits 发布 token,为每个编辑请求启动一个 EnterContractEdit,并启动汇合 Step FinishContractEdits。EnterContractEdit 交接给 EditContract,由它记录编辑开始的时间。汇合 Step 用每次编辑的记录完成 Flow,这些编辑的时间段互不重叠。
编辑请求上的标志用来模拟其他出口。交接失败,以及 SaveContractEdit 失败两次的编辑,都会进入 ReleaseContractEditToken。被撤回的编辑从 EditContract 提前离开。每种情况都会归还 token,其他审核人仍能轮到。
CONTRACT_EDIT_TOKEN = Channel("contractEditToken", str)
CONTRACT_EDIT_FINISHED = Channel("contractEditFinished", ContractEditRecord)
CONTRACT_EDIT_RETRY = RetryPolicy(
initial_interval=timedelta(seconds=1), maximum_attempts=2
)
class EnterContractEdit(Step[ContractEdit]):
"""Takes the token and hands off; it does no protected work, so canceling it is safe."""
def get_step_options(self) -> StepOptions:
return StepOptions(execute_retry=CONTRACT_EDIT_RETRY).on_execute_failure_proceed_to(
ReleaseContractEditToken
)
def wait_for(self, context: Context, edit: ContractEdit) -> Wait:
return Wait.until(CONTRACT_EDIT_TOKEN.for_one())
def execute(self, context: Context, edit: ContractEdit) -> StepDecision:
if edit.should_fail_handoff:
raise ContractEditError("contract handoff failed")
return go_to(EditContract, edit)
class EditContract(Step[ContractEdit]):
"""The first Step that works on the contract. Never cancel it."""
def get_step_options(self) -> StepOptions:
return StepOptions(execute_retry=CONTRACT_EDIT_RETRY).on_execute_failure_proceed_to(
ReleaseContractEditToken
例子: examples/python/dex_examples/patterns/critical-section/contract_edit_flow.py
var (
ContractEditToken = dex.DefineChannel[string]("contractEditToken")
ContractEditFinished = dex.DefineChannel[ContractEditRecord]("contractEditFinished")
errContractHandoff = errors.New("contract handoff failed")
errContractEdit = errors.New("contract edit failed")
contractEditRetry = &dex.RetryPolicy{InitialInterval: time.Second, MaximumAttempts: 2}
)
// EnterContractEdit takes the token and hands off; it does no protected work,
// so canceling it is safe.
type EnterContractEdit struct{ dex.StepDefaults }
func (EnterContractEdit) GetStepOptions() *dex.StepOptions {
return &dex.StepOptions{
ExecuteRetry: contractEditRetry,
ExecuteFailure: dex.ProceedToOnExecuteFailure(ReleaseContractEditToken{}, nil),
}
}
func (EnterContractEdit) WaitFor(dex.Context, ContractEdit) (*dex.Wait, error) {
return dex.Until(ContractEditToken.ForOne()), nil
}
func (EnterContractEdit) Execute(_ dex.Context, edit ContractEdit) (*dex.StepDecision, error) {
if edit.ShouldFailHandoff {
return nil, errContractHandoff
}
return dex.GoTo(EditContract{}, edit), nil
}
public static final Channel<String> contractEditToken =
Channel.define("contractEditToken", String.class);
public static final Channel<ContractEditRecord> contractEditFinished =
Channel.define("contractEditFinished", ContractEditRecord.class);
/** Routes an execute failure after the token was consumed to the Step that returns it. */
private static StepOptions contractEditOptions() {
return StepOptions.newBuilder()
.executeRetry(RetryPolicy.newBuilder()
.initialInterval(Duration.ofSeconds(1))
.maximumAttempts(2)
.build())
.onExecuteFailureProceedTo(ReleaseContractEditToken.class)
.build();
}
/** Takes the token and hands off; it does no protected work, so canceling it is safe. */
static final class EnterContractEdit implements Step<ContractEdit> {
@Override
public Class<ContractEdit> getInputType() {
return ContractEdit.class;
}
@Override
public StepOptions getStepOptions() {
return contractEditOptions();
}
@Override
public Wait waitFor(final Context context, final ContractEdit edit) {
例子: examples/java/src/main/java/io/superdurable/dex/patterns/criticalsection/ContractEditFlow.java
export const contractEditToken = new Channel("contractEditToken", stringCodec);
export const contractEditFinished = new Channel(
"contractEditFinished",
jsonCodec<ContractEditRecord>({ typeName: "ContractEditRecord" }),
);
/**
* Takes the token and hands off; it does no protected work, so canceling it
* is safe.
*/
class EnterContractEdit implements Step<ContractEdit> {
public getStepType(): string {
return "EnterContractEdit";
}
public getStepOptions(): StepOptions {
return {
executeRetry: { initialIntervalMs: 1_000, maximumAttempts: 2 },
executeFailure: ExecuteFailure.proceedTo(ReleaseContractEditToken),
};
}
public waitFor(_context: Context, _edit: ContractEdit): Wait {
return Wait.until(contractEditToken.forOne());
}
public execute(_context: Context, edit: ContractEdit): StepDecision {
if (edit.shouldFailHandoff) {
throw new Error("contract handoff failed");
}
例子: examples/typescript/src/patterns/critical-section/contract-edit-flow.ts
pub static CONTRACT_EDIT_TOKEN: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("contractEditToken"));
pub static CONTRACT_EDIT_FINISHED: LazyLock<Channel<ContractEditRecord>> =
LazyLock::new(|| Channel::new("contractEditFinished"));
/// Takes the token and hands off; it does no protected work, so canceling
/// it is safe.
#[derive(Default)]
struct EnterContractEdit;
impl Step for EnterContractEdit {
type Input = ContractEdit;
fn options(&self) -> StepOptions<Self::Input> {
contract_edit_options()
}
fn wait_for(&self, _context: &mut Context, _edit: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::until(CONTRACT_EDIT_TOKEN.for_one()))
}
fn execute(&self, _context: &mut Context, edit: Self::Input) -> HandlerResult<StepDecision> {
if edit.should_fail_handoff {
return Err(HandlerError::new(
"ContractHandoffFailed",
"contract handoff failed",
));
}
Ok(StepDecision::go_to(&EditContract, edit))
}
例子: examples/rust/src/control_patterns/critical_section/flow.rs