微服务编排
查看 Markdown一个 Flow 最多调用四个 API。API 2 和 API 3 并行运行。API 3 的分支先等待回调或 24 小时超时,再发出调用。
SDK: Python · Go · TypeScript · Java · Rust
上图和下面说明中的名称来自 Python 示例。Rust 示例使用另一套名称,见 Rust 示例。
产品需求
流程以一个数据值启动。它必须:
- 调用 API 1,并保存这个值。
- 然后并行调用 API 2 和 API 3。
- 调用 API 3 之前,等另一个服务报告就绪,最多等 24 小时。
- 如果先过了 24 小时,在 API 3 之后再调用 API 4。
- 流程运行期间,允许调用方交换这个值:在一次操作中存入新值并取回旧值。
API 2、API 3 和 API 4 使用各自运行时的当前值。
Flow 设计
CallAPI1 把值存入 data Attribute,并把 CallAPI2 和 CallAPI3 作为并行 Step 启动。每个 API 调用都是一个独立的 Step。所以重试 API 3 不会重复 API 1 或 API 2。
CallAPI2 返回 DeadEnd,结束自己的分支。另一个分支完成 Flow。
CallAPI3 用 AnyOf 等待一条 Ready Channel 消息或一个 24 小时的 Timer。它的 Execute 调用 API 3,然后检查 Timer 是否触发。如果触发了,Flow 继续到 CallAPI4。
Swap RPC 锁住 data,写入新值并返回旧值。每个分支在运行时读取 data。所以如果交换发生在两次读取之间,CallAPI2 和 CallAPI3 会拿到不同的值。
真实的 API 调用需要幂等键,因为被中断的 Step 可能再次运行。示例没有传:它调用的是本地 stub。
核心实现
每个标签页先展示带 Swap RPC 的 Flow,再展示 CallAPI1 和 CallAPI3。
class OrchestrationFlow(Flow[str]):
data = Attribute("data", str)
ready = Channel[None]("Ready", type(None))
def __init__(self, service: MyDependencyService) -> None:
self.service = service
self.call_api4 = CallAPI4(service, self.data)
self.call_api3 = CallAPI3(service, self.data, self.ready, self.call_api4)
self.call_api2 = CallAPI2(service, self.data)
self.call_api1 = CallAPI1(service, self.data, self.call_api2, self.call_api3)
def get_steps(self) -> StepList[str]:
return StepList.start_step(self.call_api1).other_steps(
self.call_api2,
self.call_api3,
self.call_api4,
)
def get_persistence_schema(self) -> PersistenceSchema:
return PersistenceSchema.of(self.data, self.ready)
@rpc(lock_attributes=(data.lock(),))
def swap(self, context: Context, new_data: str) -> RPCResult[str]:
old_data = self.data.get(context)
# CallAPI1 would overwrite a value written before it stores data.
if old_data is None:
raise RuntimeError("data is not ready yet")
self.data.set(context, new_data)
return RPCResult(old_data)
class CallAPI1(Step[str]):
def execute(self, context: Context, input: str) -> StepDecision:
self.service.call_api1(input)
self.data.set(context, input)
return go_to_many(
StepMovement.of(CallAPI2, None),
StepMovement.of(CallAPI3, None),
)
class CallAPI3(Step[None]):
def wait_for(self, context: Context, input: None) -> Wait:
return Wait.any_of(
Timer.by_duration(timedelta(hours=24)),
self.ready.for_one(),
)
def execute(self, context: Context, input: None) -> StepDecision:
value = self.data.get(context)
self.service.call_api3(value)
if context.has_timer_fired():
return go_to(CallAPI4, None)
return graceful_complete(value)
例子: examples/python/dex_examples/products/microservices/orchestration_flow.py
type OrchestrationFlow struct {
dex.FlowDefaults
service service.MyService
}
func NewOrchestrationFlow(applicationService service.MyService) *OrchestrationFlow {
return &OrchestrationFlow{service: applicationService}
}
func (flow *OrchestrationFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(callAPI1{service: flow.service}),
dex.DefineStep(callAPI2{service: flow.service}),
dex.DefineStep(callAPI3{service: flow.service}),
dex.DefineStep(callAPI4{service: flow.service}),
}
}
func (flow *OrchestrationFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.Swap, &dex.RPCOptions{
LockAttributes: []dex.AttributeLock{dex.LockAttribute(Data)},
}),
dex.DefineRPC(flow.SignalReady, nil),
dex.DefineRPC(flow.GetData, nil),
}
}
func (*OrchestrationFlow) GetPersistenceSchema() dex.PersistenceSchema {
return dex.PersistenceSchema{
Attributes: []dex.AttributeDef{Data},
Channels: []dex.ChannelDef{Ready},
}
}
func (*OrchestrationFlow) Swap(
ctx dex.Context,
newData string,
) (*dex.RPCResult[string], error) {
oldData, err := Data.Get(ctx)
if err != nil {
return nil, err
}
if err := Data.Set(ctx, newData); err != nil {
return nil, err
}
return &dex.RPCResult[string]{Output: oldData}, nil
}
func (step callAPI1) Execute(
ctx dex.Context,
input string,
) (*dex.StepDecision, error) {
step.service.CallAPI1(input)
if err := Data.Set(ctx, input); err != nil {
return nil, err
}
return dex.GoToMany(
dex.MovementOf(callAPI2{}, nil),
dex.MovementOf(callAPI3{}, nil),
), nil
}
func (callAPI3) WaitFor(
dex.Context,
dex.None,
) (*dex.Wait, error) {
return dex.AnyOf(
dex.Timer(24*time.Hour),
Ready.ForOne(),
), nil
}
func (step callAPI3) Execute(
ctx dex.Context,
_ dex.None,
) (*dex.StepDecision, error) {
data, err := Data.Get(ctx)
if err != nil {
return nil, err
}
step.service.CallAPI3(data)
if ctx.HasTimerFired() {
return dex.GoTo(callAPI4{}, nil), nil
}
return dex.GracefulComplete(data), nil
}
@Component
public class OrchestrationFlow implements Flow<String> {
public final Attribute<String> data = Attribute.define("data", String.class);
public final Channel<Void> ready = Channel.define("Ready", Void.class);
private final MyDependencyService service;
private final CallAPI1 callAPI1 = new CallAPI1();
private final CallAPI2 callAPI2 = new CallAPI2();
private final CallAPI3 callAPI3 = new CallAPI3();
private final CallAPI4 callAPI4 = new CallAPI4();
public OrchestrationFlow(final MyDependencyService service) {
this.service = service;
}
@Override
public StepList<String> getSteps() {
return StepList.startStep(callAPI1).otherSteps(callAPI2, callAPI3, callAPI4);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(data, ready);
}
@RPC(lockAttributes = {"data"})
public RPCResult<String> swap(final Context context, final String newData) {
final String oldData = data.get(context);
// CallAPI1 would overwrite a value written before it stores data.
if (oldData == null) {
throw new IllegalStateException("data is not ready yet");
}
data.set(context, newData);
return RPCResult.of(oldData);
}
final class CallAPI1 implements Step<String> {
@Override
public StepDecision execute(final Context context, final String input) {
service.callAPI1(input);
data.set(context, input);
return StepDecision.goToMany(
StepMovement.of(CallAPI2.class, null),
StepMovement.of(CallAPI3.class, null));
}
}
final class CallAPI3 implements Step<Void> {
@Override
public Wait waitFor(final Context context, final Void input) {
return Wait.anyOf(Timer.byDuration(Duration.ofHours(24)), ready.forOne());
}
@Override
public StepDecision execute(final Context context, final Void input) {
final String value = data.get(context);
service.callAPI3(value);
if (context.hasTimerFired()) {
return StepDecision.goTo(CallAPI4.class, null);
}
return StepDecision.gracefulComplete(value);
}
}
例子: examples/java/src/main/java/io/superdurable/dex/products/microservices/OrchestrationFlow.java
const data = new Attribute("data", stringCodec);
export class OrchestrationFlow implements Flow<string> {
public readonly data = data;
public readonly callAPI1 = new CallAPI1(this);
public readonly callAPI2 = new CallAPI2(this);
public readonly callAPI3 = new CallAPI3(this);
public readonly callAPI4 = new CallAPI4(this);
public constructor(public readonly service: MyDependencyService = myDependencyService) {}
public getFlowType(): string {
return "OrchestrationFlow";
}
public getSteps() {
return StepList.startStep(this.callAPI1).otherSteps(
this.callAPI2,
this.callAPI3,
this.callAPI4,
);
}
public getPersistenceSchema(): PersistenceSchema {
return {
attributes: [this.data],
channels: [ready],
};
}
@rpc({ inputCodec: stringCodec, outputCodec: stringCodec, lockAttributes: [data.lock()] })
public swap(context: Context, newData: string): RPCResult<string> {
const oldData = this.data.get(context);
// CallAPI1 would overwrite a value written before it stores data.
if (oldData === undefined) {
throw new Error("data is not ready yet");
}
this.data.set(context, newData);
return { output: oldData };
}
class CallAPI1 implements Step<string> {
public execute(context: Context, input: string): StepDecision {
this.flow.service.callAPI1(input);
this.flow.data.set(context, input);
return goToMany(
StepMovement.of(CallAPI2, undefined),
StepMovement.of(CallAPI3, undefined),
);
}
}
class CallAPI3 implements Step<void> {
public waitFor(_context: Context, _input: void): Wait {
return Wait.anyOf(Timer.byDuration(DAY_MS), ready.forOne());
}
public execute(context: Context, _input: void): StepDecision {
const value = this.flow.data.get(context);
this.flow.service.callAPI3(value);
if (context.hasTimerFired()) {
return goTo(CallAPI4, undefined);
}
return gracefulComplete(value);
}
}
例子: examples/typescript/src/products/microservices/orchestration-flow.ts
pub const SWAP_ORCHESTRATION_DATA: Rpc<String, String> = Rpc::new("SwapOrchestrationData");
pub const SIGNAL_ORCHESTRATION_READY: Rpc<(), ()> = Rpc::new("SignalOrchestrationReady");
pub static DATA: LazyLock<Attribute<String>> =
LazyLock::new(|| Attribute::new("orchestration-data"));
pub static READY: LazyLock<Channel<()>> = LazyLock::new(|| Channel::new("orchestration-ready"));
#[derive(Default)]
pub struct OrchestrationFlow {
call_api_one: CallApiOne,
call_api_two: CallApiTwo,
call_api_three: CallApiThree,
call_api_four: CallApiFour,
}
impl Flow for OrchestrationFlow {
type StartInput = String;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.call_api_one)
.and(&self.call_api_two)
.and(&self.call_api_three)
.and(&self.call_api_four)
}
fn persistence(&self) -> PersistenceSchema {
PersistenceSchema::new().attribute(&DATA).channel(&READY)
}
fn rpcs(&self) -> RpcList<Self> {
RpcList::new()
.function(SWAP_ORCHESTRATION_DATA.lock(DATA.lock()), Self::swap)
.procedure_without_input(SIGNAL_ORCHESTRATION_READY, Self::signal_ready)
}
}
impl Step for CallApiOne {
type Input = String;
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
context.record_event("api-one", input.clone())?;
DATA.set(context, input)?;
Ok(StepDecision::go_to_many([
StepMovement::to(&CallApiTwo, ()),
StepMovement::to(&CallApiThree, ()),
]))
}
}
impl Step for CallApiThree {
type Input = ();
fn wait_for(&self, _context: &mut Context, _input: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::any_of([
READY.for_one(),
Timer::by_duration(Duration::from_secs(24 * 60 * 60)),
]))
}
fn execute(&self, context: &mut Context, _input: Self::Input) -> HandlerResult<StepDecision> {
let data = DATA.get(context)?.unwrap_or_default();
context.record_event("api-three", data.clone())?;
if context.has_timer_fired(0) {
return Ok(StepDecision::go_to(&CallApiFour, ()));
}
Ok(StepDecision::graceful_complete(data))
}
}
Rust 示例
Rust 示例用另一套名称运行同一个 Flow。它的 Attribute 是 orchestration-data,Channel 是 orchestration-ready,Step 是 CallApiOne 到 CallApiFour。每个 Step 记录一个事件,代替 API 调用。运行中的调用对它同样适用。
运行
按在 playground 里运行一个示例启动一种语言的示例。在 examples playground 中选择 Microservices,用同一个 Flow ID 依次调用 Start、Swap data (RPC) 和 Signal ready。CallAPI1 保存值之前,Swap 会失败;这时再调用一次即可。
下面的截图来自一次使用自选值的运行。它以 initial-data 启动,Swap 把它替换为 updated-data。playground 以 test initial data 启动,并换入 data 字段的值。Ready 在 Timer 触发前到达,所以 CallAPI4 没有运行。
在 Dex Web 中打开 Events。Timeline 显示 Swap RPC 和 Ready 消息,Graph 显示哪些 Step 运行了。

