等待 Attribute 匹配
查看 MarkdownWaitForAttributeMatch 在某个 Attribute 满足比较条件时返回,例如 revision 大于调用方上次看到的值。当调用方需要在持久化业务状态变化后刷新,而 Flow 继续运行时,使用这个模式。
工作方式
这个 Attribute 由应用定义,含义也由应用决定。等待只检查这个 Attribute 的值。
- 保留一个 revision。 常见做法是定义一个初始值为 0 的整数 revision Attribute。
- 每次修改都推进它。 所有修改业务状态的 Step 和 RPC 都声明同一把 lock。持有 lock 时,它读取 revision、加一、写入业务状态,再写入新的 revision。
- 等待,然后刷新。 调用方等到 revision 大于自己上次看到的值。等待返回当前的 revision。随后,调用方通过 read RPC 读取新状态,或者用 GetAttributes 读取 Attribute。
在锁内推进 revision
Job Posting 示例使用一个 Attribute lock 串行化 update RPC。它在写入状态的同一次 invocation 中推进 UpdateVersion。
@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
func (flow *JobPostingFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.Get, nil),
dex.DefineRPC(flow.GetWithStrongConsistency, nil),
dex.DefineRPC(flow.Update, &dex.RPCOptions{
LockAttributes: []dex.AttributeLock{dex.LockAttribute(UpdatePostingLock)},
}),
}
}
func (*JobPostingFlow) Update(
ctx dex.Context,
input JobInfo,
) (*dex.RPCResult[int], error) {
version, err := UpdateVersion.Get(ctx)
if err != nil {
return nil, err
}
version++
if err := Title.Set(ctx, input.Title); err != nil {
return nil, err
}
if err := JobDescription.Set(ctx, input.Description); err != nil {
return nil, err
}
if err := LastUpdateTimeMillis.Set(ctx, time.Now().UnixMilli()); err != nil {
return nil, err
}
if input.Notes != "" {
if err := Notes.Set(ctx, input.Notes); err != nil {
return nil, err
}
}
if err := UpdateVersion.Set(ctx, version); err != nil {
return nil, err
}
update := PostingUpdate{
Version: version,
IdempotencyKey: fmt.Sprintf("%s:%d", ctx.FlowID(), version),
Posting: input,
}
if err := LinkedInPostingUpdates.Publish(ctx, update); err != nil {
return nil, err
}
if err := IndeedPostingUpdates.Publish(ctx, update); err != nil {
return nil, err
}
return &dex.RPCResult[int]{Output: version}, nil
}
@RPC(lockAttributes = {"UpdatePostingLock"})
public RPCResult<Integer> update(final Context context, final JobInfo input) {
final int version = updateVersion.get(context) + 1;
title.set(context, input.title);
jobDescription.set(context, input.description);
lastUpdateTimeMillis.set(context, System.currentTimeMillis());
if (input.notes != null) {
notes.set(context, input.notes);
}
updateVersion.set(context, version);
final PostingUpdate update = new PostingUpdate(
version,
context.getFlowId() + ":" + version,
input);
linkedInPostingUpdates.publish(context, update);
indeedPostingUpdates.publish(context, update);
return RPCResult.of(version);
}
例子: examples/java/src/main/java/io/superdurable/dex/products/jobpost/JobPostingFlow.java
@rpc({
inputCodec: jobInfoCodec,
outputCodec: doubleCodec,
lockAttributes: [updatePostingLock.lock()],
})
public update(context: Context, input: JobInfo): RPCResult<number> {
const version = this.updateVersion.get(context) + 1;
this.title.set(context, input.title);
this.jobDescription.set(context, input.description);
this.lastUpdateTimeMillis.set(context, BigInt(Date.now()));
if (input.notes !== undefined && input.notes.length > 0) {
this.notes.set(context, input.notes);
}
this.updateVersion.set(context, version);
const update = {
version,
idempotencyKey: `${context.flowId}:${version}`,
posting: input,
};
this.linkedInPostingUpdates.publish(context, update);
this.indeedPostingUpdates.publish(context, update);
return {
output: version,
};
}
例子: examples/typescript/src/products/job-post/job-post-flow.ts
RpcList::new()
.function_without_input(GET_JOB_POST, Self::get_job_post)
.function(
UPDATE_JOB_POST.lock(UPDATE_POSTING_LOCK.lock()),
Self::update_job_post,
)
let version = UPDATE_VERSION.get_required(context)? + 1;
POST.set(context, replacement.clone())?;
TITLE.set(context, replacement.title.clone())?;
DESCRIPTION.set(context, replacement.description.clone())?;
UPDATE_VERSION.set(context, version)?;
let update = PostingUpdate {
version,
idempotency_key: format!("{}:{version}", context.flow_id()),
posting: replacement,
};
LINKEDIN_POSTING_UPDATES.publish(context, update.clone())?;
INDEED_POSTING_UPDATES.publish(context, update)?;
Ok(RpcResult::new(version))
等待后刷新
等待按 Flow ID 定位活跃的 run,并接收 Attribute 和比较条件。它返回大于调用方 watermark 的 revision 后,controller 再调用 read RPC。
revision = await app_state.client.wait_for_attribute_match(
flow_id,
app_state.job_post.update_version,
AttributeMatch.greater_than(required_int_query("lastRevision")),
WaitForAttributeOptions(),
)
job_info = await app_state.client.invoke_rpc(app_state.job_post.get, flow_id)
例子: examples/python/dex_examples/products/job-post/controller.py
var revision int
err = controller.client.WaitForAttributeMatch(
request.Request.Context(),
flowID,
UpdateVersion,
sdk.AttributeMatchGreaterThan(lastRevision),
&revision,
sdk.WaitForAttributeOptions{},
)
var jobInfo JobInfo
err = controller.client.InvokeRPC(
request.Request.Context(),
flowID,
controller.flow.Get,
nil,
&jobInfo,
)
final int revision = client.waitForAttributeMatch(
workflowId,
flow.updateVersion,
AttributeMatch.greaterThan(lastRevision),
WaitForAttributeOptions.newBuilder().build());
final JobPostingFlow stub = client.newRpcStub(JobPostingFlow.class, workflowId);
final Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put("revision", revision);
response.put("jobInfo", client.invokeRPC(stub::get));
例子: examples/java/src/main/java/io/superdurable/dex/products/jobpost/JobPostingController.java
const revision = await client.waitForAttributeMatch(
workflowId,
jobPostingFlow.updateVersion,
AttributeMatch.greaterThan(lastRevision),
{},
);
const jobInfo = await client.invokeRPC(jobPostingFlow.get, workflowId);
let revision = client.wait_for_attribute_match(
&flow_id,
&UPDATE_VERSION,
AttributeMatch::greater_than(query.last_revision),
WaitForAttributeOptions::new(),
)?;
let job_info: JobPost = client.invoke_rpc_without_input(&flow_id, GET_JOB_POST)?;
规则和陷阱
- 把 revision 当作 watermark。 等待返回当前值,可能跳过中间的值。如果状态快速地从 0 变成 1、2、3,一次等待大于 0 的调用可能直接返回 3。
- 有截止时间的入口要设请求超时。 如果在 HTTP endpoint 或其他有自己截止时间的入口里执行等待,设置
RequestTimeout。见等待超时与上限。
支持的 operator、被拒绝的比较类型和 active Flow 规则见等待 Attribute 匹配。完整示例是 职位发布 用例。