高级:短生命周期父 Flow
查看 Markdown处理完排队的请求后完成父 Flow,不会丢掉最后时刻到达的请求。
Init Step 向 RequestChannel 写入请求,初始化 CurrSubFlowNum,并启动 N 个 worker。CurrSubFlowNum 记录正在运行的 SubFlow 数量。HandleRequest Step 的 Execute 持有它的 Attribute lock 并加一;HandleSubFlow Step 的 Execute 持有同一把 lock 并减一。
最后一个 active worker 返回 ForceCompleteIfChannelsEmpty。Dex 检查 RequestChannel,只有为空才完成 Flow。如果 RPC 已先发布新请求,Dex 改为再调度一个 HandleRequest Step。检查和完成一起发生,中间不会插进新请求。在应用代码里先查 size 再完成做不到这一点。
核心实现
DEFAULT_CONCURRENCY = 10
MAX_BUFFERED_REQUESTS = 100
class ShortLiveInit(Step[ParentInput]):
def __init__(
self,
request_channel: Channel[str],
curr_subflow_num: Attribute[int],
) -> None:
self.request_channel = request_channel
self.curr_subflow_num = curr_subflow_num
def get_step_type(self) -> str:
return "Init"
def execute(self, context: Context, input: ParentInput) -> StepDecision:
for request in input.requests:
self.request_channel.publish(context, request)
self.curr_subflow_num.set(context, 0)
concurrency = input.concurrency if input.concurrency > 0 else DEFAULT_CONCURRENCY
return go_to_many(
*(StepMovement.of(ShortLiveHandleRequest, None) for _ in range(concurrency))
)
class ShortLiveHandleRequest(Step[None]):
def __init__(
self,
request_channel: Channel[str],
例子: examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py
const (
DefaultConcurrency = 10
MaxBufferedRequests = 100
)
var (
RequestChannel = dex.DefineChannel[string]("RequestChannel")
CurrSubFlowNum = dex.DefineAttribute[int]("CurrSubFlowNum")
)
type AdvancedShortLiveParentFlow struct {
dex.FlowDefaults
exampleFlow *ExampleSubFlow
}
func NewAdvancedShortLiveParentFlow(exampleFlow *ExampleSubFlow) *AdvancedShortLiveParentFlow {
return &AdvancedShortLiveParentFlow{exampleFlow: exampleFlow}
}
func (flow *AdvancedShortLiveParentFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(shortLiveInit{}),
dex.DefineStep(shortLiveHandleRequest{}),
dex.DefineStep(shortLiveHandleSubFlow{exampleFlow: flow.exampleFlow}),
}
}
func (flow *AdvancedShortLiveParentFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{dex.DefineRPC(flow.SendRequest, nil)}
}
例子: examples/go/patterns/parallel-subflows/advanced_short_live_parent_flow.go
public class AdvancedShortLiveParentFlow implements Flow<ParentInput> {
public static final int DEFAULT_CONCURRENCY = 10;
public static final int MAX_BUFFERED_REQUESTS = 100;
public final Channel<String> requestChannel = Channel.define("RequestChannel", String.class);
public final Attribute<Integer> currSubFlowNum = Attribute.define("CurrSubFlowNum", Integer.class);
private final InitStep initStep = new InitStep();
private final HandleRequest handleRequestStep = new HandleRequest();
private final HandleSubFlow handleSubFlowStep;
public AdvancedShortLiveParentFlow(final ExampleSubFlow exampleSubFlow) {
handleSubFlowStep = new HandleSubFlow(exampleSubFlow);
}
@Override
public StepList<ParentInput> getSteps() {
return StepList.startStep(initStep).otherSteps(handleRequestStep, handleSubFlowStep);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(requestChannel, currSubFlowNum);
}
@RPC
public RPCResult<Boolean> sendRequest(final Context context, final String request) {
if (requestChannel.size(context) >= MAX_BUFFERED_REQUESTS) {
return RPCResult.of(false);
}
const DEFAULT_CONCURRENCY = 10;
const MAX_BUFFERED_REQUESTS = 100;
const requestChannel = new Channel("RequestChannel", stringCodec);
class ShortLiveInit implements Step<ParentInput> {
public readonly inputCodec = parentInputCodec;
public constructor(private readonly flow: AdvancedShortLiveParentFlow) {}
public getStepType(): string {
return "Init";
}
public execute(context: Context, input: ParentInput): StepDecision {
for (const request of input.requests) requestChannel.publish(context, request);
this.flow.currSubFlowNum.set(context, 0);
const concurrency = input.concurrency > 0 ? input.concurrency : DEFAULT_CONCURRENCY;
return goToMany(
...Array.from({ length: concurrency }, () =>
StepMovement.of(ShortLiveHandleRequest, undefined),
),
);
}
}
class ShortLiveHandleRequest implements Step<void> {
public readonly inputCodec = voidCodec;
public constructor(private readonly flow: AdvancedShortLiveParentFlow) {}
例子: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
#[derive(Default)]
struct ShortLiveHandleSubFlow;
impl Step for ShortLiveHandleSubFlow {
type Input = String;
fn step_type(&self) -> &'static str {
"HandleSubFlowStep"
}
fn options(&self) -> StepOptions<Self::Input> {
StepOptions::new().execute_lock(CURR_SUB_FLOW_NUM.lock())
}
fn wait_for(&self, _context: &mut Context, request: String) -> HandlerResult<Wait> {
let child = ExampleSubFlow::default();
Ok(Wait::until(
SubFlow::run(&child, request).map_err(HandlerError::from_error)?,
))
}
fn execute(&self, context: &mut Context, _request: String) -> HandlerResult<StepDecision> {
let current = CURR_SUB_FLOW_NUM.get(context)?.unwrap_or(1) - 1;
CURR_SUB_FLOW_NUM.set(context, current)?;
if current == 0 {
return Ok(StepDecision::force_complete_if_channels_empty(
(),
StepMovement::to(&ShortLiveHandleRequest, ()),
[REQUEST_CHANNEL.when_empty()],
));
}
Ok(StepDecision::go_to(&ShortLiveHandleRequest, ()))
}
}
空批次和提前到达的请求
示例做了简化:Flow 一启动,它的 RPC 就能发布请求,而且即使批次为空也启动 worker。父 Flow 如果要处理空批次,就加一个接收开关:
- 只有第一个 Step 把启动批次排进队列后,接收才开放。RPC 读取这个开关,在那之前拒绝请求。于是空的启动批次可以直接完成,因为不可能有请求在等待。
- 修改子 Flow 计数的 Step 锁住开关所在的 Attribute。RPC 不加 lock。
- 缓冲上限是软上限。并发的 RPC 可能读到同一个大小,而且 Channel 大小只计算排队中的请求,不包括已经领取的工作。需要硬上限时,用原子的准入,比如加锁的预留。在启动 Flow 的地方用上限检查启动批次。
- 调用方必须确认每个请求都已处理时,消费的 Step 在同一次提交里记录请求的业务 ID,调用方读取这份记录;见 确认消息已处理(英文)。
以下步骤描述带接收开关的变体。它额外的 Step AdmitBatch 不在上面的图中。
AdmitBatch持有接收开关 Attribute 的 lock,接收启动批次。批次为空时返回GracefulComplete,因为接收从未开放。- 否则
AdmitBatch在同一次提交中把每个请求排进RequestsChannel、开放接收、把运行中子 Flow 计数设为 0,并在HandleRequest中启动 worker。 sendRequest不加 lock 地读取接收开关 Attribute。只有在接收开放且当前队列长度低于上限时,它才接受请求,并把它排进同一个 Channel。