职位发布
查看 Markdown保存一条职位信息并支持搜索,同时把每个已接受的更新按顺序发送到 LinkedIn 和 Indeed。
SDK: Python · Go · TypeScript · Java · Rust
上图和本页描述覆盖 Python、Go、Java 和 TypeScript 示例。Go 示例把第一个 Step 命名为 Init。Rust 示例有几处名称不同,见 Rust 示例。
产品需求
每个 Flow 在整个生命周期内代表一条职位信息。它必须:
- 保存职位名称、描述和备注。搜索按名称查找职位;描述只保存。
- 一次接受一个替换后的职位信息,并给每个已接受的更新分配下一个版本号。
- 立即返回这个版本,不等招聘网站。
- 把每个已接受的更新按版本顺序发送到 LinkedIn 和 Indeed。每个招聘网站按自己的进度接收。
- 每次招聘网站调用最多重试一小时:首次间隔 3 秒,最大间隔 60 秒,最多 100 次。
- 删除职位时停止。
Flow 设计
成功的那次 InitStep 为每个招聘网站启动一个 consumer Step。每个 consumer 在自己的 Channel 上等一条消息,发送这次更新,然后回到自身。
update RPC 声明对 UpdatePostingLock 的 lock。这个 Attribute 没有值。所以 Dex 一次只运行一个更新。每次更新递增 UpdateVersion,保存职位信息,并把同一个 PostingUpdate 发布到 LinkedInPostingUpdates 和 IndeedPostingUpdates。版本按 Dex 接受更新的先后排列,而不是按调用方发出请求的先后。
设计靠四个选择:
- 实体 Flow:Flow ID 就是这条职位,可检索的状态保存在 Attribute 中。
Title以text1建索引。 - 状态和消息一起保存:Dex 把职位信息和两条 Channel 消息作为同一个 RPC 结果保存。已接受的更新总会同时排进两个招聘网站的队列。
- 消息自带快照:每条消息都带着 RPC 当时看到的职位信息。consumer 从不读之后可能已改变的 Attribute。
- FIFO consumer 循环:consumer 处理完一条消息再回到自身。它重试期间,该招聘网站的后续消息都在等待,所以 v2 永远排在 v1 之后。
每个招聘网站只有一个 consumer,顺序由它的 Channel 保证。所以 consumer Step 不需要 lock。
每条消息都带幂等键 <Flow ID>:<version>。招聘网站调用可能已经成功但响应丢失,重试会再发一次同一个更新。招聘网站,或者它前面的适配器,必须按这个键丢弃重复请求。示例的桩服务只打印这条消息,其中包含这个键。没有哪个示例会向真实的招聘网站发送带键的请求。
每个 consumer 独立重试,所以慢的招聘网站只拖慢自己的更新。某个招聘网站用完重试后,Flow 失败,因为 consumer 没有失败路由。
删除会停止 Flow。仍在排队的更新不再发送,正在发送的那次仍可能完成。按产品的删除规则决定需要怎样处理。
核心实现
注意带 lock 的 update RPC 把同一个更新发布到两个 Channel,以及 consumer 循环。每个标签页都链接到对应的可运行示例。
UPDATE_VERSION = Attribute("UpdateVersion", int)
UPDATE_POSTING_LOCK = Attribute("UpdatePostingLock", type(None))
LINKEDIN_POSTING_UPDATES = Channel("LinkedInPostingUpdates", PostingUpdate)
INDEED_POSTING_UPDATES = Channel("IndeedPostingUpdates", PostingUpdate)
# dex:group group-id:setup group-label:"Setup"
# dex:explanation text:"Start one posting update consumer for each job board."
class InitStep(Step[None]):
def execute(self, context: Context, input: None) -> StepDecision:
return go_to_many(
StepMovement.of(UpdateLinkedInPosting, None),
StepMovement.of(UpdateIndeedPosting, None),
)
# dex:group group-id:linkedin group-label:"LinkedIn"
# dex:explanation text:"Apply each queued posting update to LinkedIn in order."
class UpdateLinkedInPosting(Step[None]):
def __init__(self, service: MyDependencyService) -> None:
self.service = service
def get_step_options(self) -> StepOptions:
return StepOptions(execute_retry=JOB_BOARD_UPDATE_RETRY)
def wait_for(self, context: Context, input: None) -> Wait:
return Wait.until(LINKEDIN_POSTING_UPDATES.for_one())
def execute(self, context: Context, input: None) -> StepDecision:
update = LINKEDIN_POSTING_UPDATES.results(context)[0]
self.service.update_external_system(
f"update LinkedIn job posting v{update.version} "
f"[{update.idempotency_key}]: {update.posting.title}"
)
return go_to(UpdateLinkedInPosting, None)
class JobPostingFlow(Flow[None]):
# dex:indexed-attribute attribute-key:Title index-key:text1 index-type:fulltext value-type:string description:"Job posting title"
title = Attribute("Title", str, AttributeIndex(IndexType.FULL_TEXT, "text1"))
job_description = Attribute("JobDescription", str)
# dex:indexed-attribute attribute-key:LastUpdateTimeMillis index-key:int1 index-type:int value-type:int64 description:"Last update time in milliseconds"
last_update_time_millis = Attribute(
"LastUpdateTimeMillis",
int,
AttributeIndex(IndexType.INT, "int1"),
)
notes = Attribute("Notes", str)
update_version = UPDATE_VERSION
update_posting_lock = UPDATE_POSTING_LOCK
linkedin_posting_updates = LINKEDIN_POSTING_UPDATES
indeed_posting_updates = INDEED_POSTING_UPDATES
def __init__(self, service: MyDependencyService) -> None:
self.service = service
self.init = InitStep()
self.update_linkedin_posting = UpdateLinkedInPosting(service)
self.update_indeed_posting = UpdateIndeedPosting(service)
def get_steps(self) -> StepList[None]:
return StepList.start_step(self.init).other_steps(
self.update_linkedin_posting,
self.update_indeed_posting,
)
@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
type JobPostingFlow struct {
dex.FlowDefaults
service service.MyService
}
func (flow *JobPostingFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(Init{}),
dex.DefineStep(UpdateLinkedInPosting{service: flow.service}),
dex.DefineStep(UpdateIndeedPosting{service: flow.service}),
}
}
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
}
type Init struct {
dex.StepDefaultsNoWaitFor[dex.None]
}
func (Init) Execute(
_ dex.Context,
_ dex.None,
) (*dex.StepDecision, error) {
return dex.GoToMany(
dex.MovementOf(UpdateLinkedInPosting{}, nil),
dex.MovementOf(UpdateIndeedPosting{}, nil),
), nil
}
type UpdateLinkedInPosting struct {
dex.StepDefaults
service service.MyService
}
func (UpdateLinkedInPosting) GetStepOptions() *dex.StepOptions {
return jobBoardUpdateStepOptions()
}
func (UpdateLinkedInPosting) WaitFor(
_ dex.Context,
_ dex.None,
) (*dex.Wait, error) {
return dex.Until(LinkedInPostingUpdates.ForOne()), nil
}
func (step UpdateLinkedInPosting) Execute(
ctx dex.Context,
_ dex.None,
) (*dex.StepDecision, error) {
update, err := linkedInPostingUpdate(ctx)
if err != nil {
return nil, err
}
step.service.UpdateExternalSystem(fmt.Sprintf(
"update LinkedIn job posting v%d [%s]: %s",
update.Version,
update.IdempotencyKey,
update.Posting.Title,
))
return dex.GoTo(UpdateLinkedInPosting{}, nil), nil
}
@Component
public class JobPostingFlow implements Flow<Void> {
public final Attribute<String> title = Attribute.define(
"Title",
String.class,
new AttributeIndex(AttributeIndex.Type.FULL_TEXT, "text1"));
public final Attribute<String> jobDescription = Attribute.define("JobDescription", String.class);
public final Attribute<Long> lastUpdateTimeMillis = Attribute.define(
"LastUpdateTimeMillis",
Long.class,
new AttributeIndex(AttributeIndex.Type.INT, "int1"));
public final Attribute<String> notes = Attribute.define("Notes", String.class);
public final Attribute<Integer> updateVersion = Attribute.define("UpdateVersion", Integer.class);
public final Attribute<Void> updatePostingLock =
Attribute.define("UpdatePostingLock", Void.class);
public final Channel<PostingUpdate> linkedInPostingUpdates =
Channel.define("LinkedInPostingUpdates", PostingUpdate.class);
public final Channel<PostingUpdate> indeedPostingUpdates =
Channel.define("IndeedPostingUpdates", PostingUpdate.class);
private final MyDependencyService service;
private final InitStep init = new InitStep();
private final UpdateLinkedInPosting updateLinkedInPosting = new UpdateLinkedInPosting();
private final UpdateIndeedPosting updateIndeedPosting = new UpdateIndeedPosting();
public JobPostingFlow(final MyDependencyService service) {
this.service = service;
}
@Override
public StepList<Void> getSteps() {
return StepList.startStep(init)
.otherSteps(updateLinkedInPosting, updateIndeedPosting);
}
@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);
}
final class InitStep implements Step<Void> {
@Override
public StepDecision execute(final Context context, final Void input) {
return StepDecision.goToMany(
StepMovement.of(UpdateLinkedInPosting.class, null),
StepMovement.of(UpdateIndeedPosting.class, null));
}
}
final class UpdateLinkedInPosting implements Step<Void> {
private final StepOptions options = jobBoardUpdateOptions();
@Override
public Wait waitFor(final Context context, final Void input) {
return Wait.until(linkedInPostingUpdates.forOne());
}
@Override
public StepDecision execute(final Context context, final Void input) {
final List<PostingUpdate> updates = linkedInPostingUpdates.getConditionResults(context);
final PostingUpdate update = updates.get(0);
service.updateExternalSystem(String.format(
"update LinkedIn job posting v%d [%s]: %s",
update.version,
update.idempotencyKey,
update.posting.title));
return StepDecision.goTo(UpdateLinkedInPosting.class, null);
}
}
}
例子: examples/java/src/main/java/io/superdurable/dex/products/jobpost/JobPostingFlow.java
const title = new Attribute("Title", stringCodec, {
type: IndexType.FULL_TEXT,
indexKey: "text1",
});
const updatePostingLock = new Attribute("UpdatePostingLock", voidCodec);
const linkedInPostingUpdates = new Channel("LinkedInPostingUpdates", postingUpdateCodec);
const indeedPostingUpdates = new Channel("IndeedPostingUpdates", postingUpdateCodec);
export class JobPostingFlow implements Flow {
public readonly title = title;
public readonly jobDescription = new Attribute("JobDescription", stringCodec);
public readonly lastUpdateTimeMillis = new Attribute("LastUpdateTimeMillis", int64Codec, {
type: IndexType.INT,
indexKey: "int1",
});
public readonly notes = new Attribute("Notes", optionalStringCodec);
public readonly updateVersion = new Attribute("UpdateVersion", doubleCodec);
public readonly updatePostingLock = updatePostingLock;
public readonly linkedInPostingUpdates = linkedInPostingUpdates;
public readonly indeedPostingUpdates = indeedPostingUpdates;
public readonly init = new InitStep();
public readonly updateLinkedInPosting = new UpdateLinkedInPosting(this);
public readonly updateIndeedPosting = new UpdateIndeedPosting(this);
public constructor(public readonly service: MyDependencyService = myDependencyService) {}
public getSteps() {
return StepList.startStep(this.init).otherSteps(
this.updateLinkedInPosting,
this.updateIndeedPosting,
);
}
@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,
};
}
}
class InitStep implements Step<void> {
public execute(_context: Context, _input: void): StepDecision {
return goToMany(
StepMovement.of(UpdateLinkedInPosting, undefined),
StepMovement.of(UpdateIndeedPosting, undefined),
);
}
}
class UpdateLinkedInPosting implements Step<void> {
public constructor(private readonly flow: JobPostingFlow) {}
public getStepOptions(): StepOptions {
return jobBoardUpdateOptions();
}
public waitFor(_context: Context, _input: void): Wait {
return Wait.until(this.flow.linkedInPostingUpdates.forOne());
}
public execute(context: Context, _input: void): StepDecision {
const update = this.flow.linkedInPostingUpdates.results(context)[0];
if (update === undefined) throw new Error("LinkedIn posting update is required");
this.flow.service.updateExternalSystem(
`update LinkedIn job posting v${update.version} `
+ `[${update.idempotencyKey}]: ${update.posting.title}`,
);
return goTo(UpdateLinkedInPosting, undefined);
}
}
例子: examples/typescript/src/products/job-post/job-post-flow.ts
#[derive(Default)]
pub struct JobPostingFlow {
init: Init,
update_linkedin_posting: UpdateLinkedInPosting,
update_indeed_posting: UpdateIndeedPosting,
}
impl JobPostingFlow {
fn update_job_post(
&self,
context: &mut Context,
replacement: JobPost,
) -> HandlerResult<RpcResult<i32>> {
if POST.get_required(context)?.deleted {
return Err(HandlerError::new(
JOB_POST_DELETED,
"the job post is deleted and cannot be updated",
));
}
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))
}
fn delete_job_post(&self, context: &mut Context, notes: String) -> HandlerResult<()> {
let mut current = POST.get_required(context)?;
current.deleted = true;
current.notes = notes;
POST.set(context, current)
}
}
impl Flow for JobPostingFlow {
type StartInput = JobPost;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.init)
.and(&self.update_linkedin_posting)
.and(&self.update_indeed_posting)
}
fn rpcs(&self) -> RpcList<Self> {
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,
)
.procedure(
DELETE_JOB_POST.lock(UPDATE_POSTING_LOCK.lock()),
Self::delete_job_post,
)
}
}
#[derive(Default)]
pub struct Init;
impl Step for Init {
type Input = JobPost;
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
POST.set(context, input.clone())?;
TITLE.set(context, input.title)?;
DESCRIPTION.set(context, input.description)?;
UPDATE_VERSION.set(context, 0)?;
Ok(StepDecision::go_to_many([
StepMovement::to(&UpdateLinkedInPosting::default(), ()),
StepMovement::to(&UpdateIndeedPosting::default(), ()),
]))
}
}
#[derive(Default)]
pub struct UpdateLinkedInPosting {
service: MyDependencyService,
}
impl Step for UpdateLinkedInPosting {
type Input = ();
fn wait_for(&self, _context: &mut Context, _input: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::until(LINKEDIN_POSTING_UPDATES.for_one()))
}
fn execute(&self, context: &mut Context, _input: Self::Input) -> HandlerResult<StepDecision> {
let update = LINKEDIN_POSTING_UPDATES
.condition_results(context)?
.into_iter()
.next()
.ok_or_else(|| {
HandlerError::new("MissingPostingUpdate", "LinkedIn update is missing")
})?;
self.service.update_external_system(&format!(
"update LinkedIn job posting v{} [{}]: {}",
update.version, update.idempotency_key, update.posting.title
));
Ok(StepDecision::go_to(&UpdateLinkedInPosting::default(), ()))
}
fn options(&self) -> StepOptions<Self::Input> {
job_board_update_options()
}
}
Rust 示例
Rust 示例把第一个 Step 命名为 Init。Init 把启动输入保存为职位信息。整条职位信息保存在 job-post Attribute 中,名称保存在 job-post-title 中,并以 text1 建索引。Rust 还注册了 DeleteJobPost RPC:它把职位标记为已删除,Flow 继续运行,之后的更新会失败。下面的 playground 调用对 Rust 同样适用。
运行
按在 playground 里运行一个示例启动一种语言的示例。在 examples playground 中选择 Job posting。Create 创建一条职位并返回它的 Flow ID;其他调用把它填作 workflowId。运行两次 Update。Read 返回最新的职位信息。Search 用查询 text1 = 'Staff' 找到名称含这个词的职位。等 Dex Web 显示每个招聘网站都已完成两次执行,再运行 Delete / stop 停止 Flow。示例还提供 /products/job-post/wait-for-update,它会等到 UpdateVersion 超过给定的 lastRevision。
在 Dex Web 中打开 Events。Timeline 按顺序显示两次更新。Graph 显示每个招聘网站的两次执行,以及运行停止时被取消的等待中的 consumer。

