跳到主要内容

等待 Attribute 匹配

查看 Markdown

WaitForAttributeMatch 在某个 Attribute 满足比较条件时返回,例如 revision 大于调用方上次看到的值。当调用方需要在持久化业务状态变化后刷新,而 Flow 继续运行时,使用这个模式。

工作方式

这个 Attribute 由应用定义,含义也由应用决定。等待只检查这个 Attribute 的值。

  1. 保留一个 revision。 常见做法是定义一个初始值为 0 的整数 revision Attribute。
  2. 每次修改都推进它。 所有修改业务状态的 Step 和 RPC 都声明同一把 lock。持有 lock 时,它读取 revision、加一、写入业务状态,再写入新的 revision。
  3. 等待,然后刷新。 调用方等到 revision 大于自己上次看到的值。等待返回当前的 revision。随后,调用方通过 read RPC 读取新状态,或者用 GetAttributes 读取 Attribute。

在锁内推进 revision

Job Posting 示例使用一个 Attribute lock 串行化 update RPC。它在写入状态的同一次 invocation 中推进 UpdateVersion。

job_post_flow.pyPython
@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

等待后刷新

等待按 Flow ID 定位活跃的 run,并接收 Attribute 和比较条件。它返回大于调用方 watermark 的 revision 后,controller 再调用 read RPC。

controller.pyPython
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

规则和陷阱

  • 把 revision 当作 watermark。 等待返回当前值,可能跳过中间的值。如果状态快速地从 0 变成 1、2、3,一次等待大于 0 的调用可能直接返回 3。
  • 有截止时间的入口要设请求超时。 如果在 HTTP endpoint 或其他有自己截止时间的入口里执行等待,设置 RequestTimeout。见等待超时与上限。

支持的 operator、被拒绝的比较类型和 active Flow 规则见等待 Attribute 匹配。完整示例是 职位发布 用例。

下一步