高级:长生命周期父 Flow
查看 Markdown保持一组固定数量的 worker Step 持续运行,同时让 Flow 继续接收新请求。
Init Step 将初始请求发布到 RequestChannel,并启动 N 个 HandleRequest Step。每个 worker 取出最早的一条消息,然后跳转到 HandleSubFlow Step。这个 Step 启动并等待 ExampleSubFlow。子 Flow 完成后,它回到 HandleRequest Step;如果 Stop RPC 已把 Stopped 设为 true,它就 graceful complete。Stopped 在 Stop RPC 设置之前没有值,而且只有这个 RPC 会写它。因此,在 Init 完成之前到达的 Stop 也不会丢失。
SendRequest 在发布前检查 Channel size。Channel 达到 buffer threshold 时,它返回 false。调用方可以稍后重试,父 Flow 也不会过载。
核心实现
DEFAULT_CONCURRENCY = 10
MAX_BUFFERED_REQUESTS = 100
class LongLiveInit(Step[ParentInput]):
def __init__(self, request_channel: Channel[str]) -> None:
self.request_channel = request_channel
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)
concurrency = input.concurrency if input.concurrency > 0 else DEFAULT_CONCURRENCY
return go_to_many(
*(StepMovement.of(LongLiveHandleRequest, None) for _ in range(concurrency))
)
class LongLiveHandleRequest(Step[None]):
def __init__(self, request_channel: Channel[str]) -> None:
self.request_channel = request_channel
def get_step_type(self) -> str:
return "HandleRequest"
def wait_for(self, context: Context, input: None) -> Wait:
return Wait.until(self.request_channel.for_one())
例子: examples/python/dex_examples/patterns/parallel-subflows/advanced_long_live_parent_flow.py
const (
DefaultConcurrency = 10
MaxBufferedRequests = 100
)
var (
LongLiveRequestChannel = dex.DefineChannel[string]("RequestChannel")
Stopped = dex.DefineAttribute[bool]("Stopped")
)
type AdvancedLongLiveParentFlow struct {
dex.FlowDefaults
exampleFlow *ExampleSubFlow
}
func NewAdvancedLongLiveParentFlow(exampleFlow *ExampleSubFlow) *AdvancedLongLiveParentFlow {
return &AdvancedLongLiveParentFlow{exampleFlow: exampleFlow}
}
func (flow *AdvancedLongLiveParentFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(longLiveInit{}),
dex.DefineStep(longLiveHandleRequest{}),
dex.DefineStep(longLiveHandleSubFlow{exampleFlow: flow.exampleFlow}),
}
}
func (flow *AdvancedLongLiveParentFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.SendRequest, nil),
例子: examples/go/patterns/parallel-subflows/advanced_long_live_parent_flow.go
public class AdvancedLongLiveParentFlow 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<Boolean> stopped = Attribute.define("Stopped", Boolean.class);
private final InitStep initStep = new InitStep();
private final HandleRequest handleRequestStep = new HandleRequest();
private final HandleSubFlow handleSubFlowStep;
public AdvancedLongLiveParentFlow(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, stopped);
}
@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 LongLiveInit implements Step<ParentInput> {
public readonly inputCodec = parentInputCodec;
public getStepType(): string {
return "Init";
}
public execute(context: Context, input: ParentInput): StepDecision {
for (const request of input.requests) requestChannel.publish(context, request);
const concurrency = input.concurrency > 0 ? input.concurrency : DEFAULT_CONCURRENCY;
return goToMany(
...Array.from({ length: concurrency }, () =>
StepMovement.of(LongLiveHandleRequest, undefined),
),
);
}
}
class LongLiveHandleRequest implements Step<void> {
public readonly inputCodec = voidCodec;
public getStepType(): string {
return "HandleRequest";
}
public waitFor(_context: Context, _input: void): Wait {
例子: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
const DEFAULT_CONCURRENCY: usize = 10;
const MAX_BUFFERED_REQUESTS: usize = 100;
static REQUEST_CHANNEL: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("RequestChannel"));
static STOPPED: LazyLock<Attribute<bool>> = LazyLock::new(|| Attribute::new("Stopped"));
pub(super) const SEND_LONG_LIVE_REQUEST: Rpc<String, bool> = Rpc::new("SendLongLiveRequest");
pub(super) const STOP_LONG_LIVE_FLOW: Rpc<(), ()> = Rpc::new("StopLongLiveFlow");
#[derive(Default)]
pub struct AdvancedLongLiveParentFlow {
init: LongLiveInit,
handle_request: LongLiveHandleRequest,
handle_sub_flow: LongLiveHandleSubFlow,
}
impl AdvancedLongLiveParentFlow {
fn send_request(
&self,
context: &mut Context,
request: String,
) -> HandlerResult<RpcResult<bool>> {
if REQUEST_CHANNEL.size(context)? >= MAX_BUFFERED_REQUESTS {
return Ok(RpcResult::new(false));
}
REQUEST_CHANNEL.publish(context, request)?;
Ok(RpcResult::new(true))
}
关闭接收
上面的可运行示例演示基础变体:由后续的 Step 启动每个子 Flow,Stop RPC 在子 Flow 结束后结束 worker。它们没有可关闭的接收、共享的准入 lock 或交还请求的回复。如果父 Flow 要永久关闭接收,还要结束空闲的 worker,并交还排队中的请求:
- 关闭 RPC 把接收标记为已关闭,并发布一条关闭消息。此后接收 RPC 拒绝新请求,调用方可以把请求重新提交给新的父 Flow run。
- 两个 RPC 和
HandleRequest中 worker 的Execute声明同一个intakeClosedlock。 - 每个 worker 负责自己消费的请求。在这个 lock 下,它只提交下一步:进入不持有 lock 的
HandleChild启动子 Flow;或者在关闭后进入不持有 lock 的ReturnRequest,通过以请求为键的幂等路径交还请求(比如回复提交方),再领取下一个请求。RPC 也拿这个 lock,所以 worker 持有它时不调用其他系统或 Flow。排队的请求不会被丢掉,也不会被交还两次。 - 一个关闭 Step 等待关闭消息,然后 graceful complete。
- Channel condition 仍然优先于 graceful completion condition,所以关闭后 worker 继续领取并交还排队的请求。队列清空后,空闲的 worker 通过 graceful completion condition 被唤醒并结束自己的分支。有运行中子 Flow 的 worker 先等它结束。
- 接收 RPC 用 Channel 大小检查上限。每个 RPC 都能拿到 Channel 大小,所以父 Flow 不需要另外的等待计数器。
- graceful completion condition 需要 SDK 和 server 支持;见 Graceful completion requests(英文)。没有它时,关闭 Step 给每个 worker 发布一条唤醒消息,每个 worker 同时等待这个唤醒 Channel,它声明在请求 Channel 之后。
以下步骤描述可关闭接收的变体。它额外的 Step(例如 CloseIntake)不在上面的图中。
sendRequest持有intakeClosedlock。接收开放且当前队列长度低于上限时,它接受请求,把它排进RequestsChannel。HandleRequest中的每个 worker 等待一个排队的请求,或者等待 graceful completion 请求。- 领到请求的 worker 持有
intakeClosedlock,提交进入HandleChild的一步,由它在不持有 lock 时启动子 Flow。关闭之后,它改为进入ReturnRequest,由它在不持有 lock 时交还请求,然后等待下一个请求。 - 本次等待经 graceful completion 请求唤醒、且没有消费请求的 worker 结束自己的分支。
closeIntake持有intakeClosedlock,把接收标记为已关闭,并发布一条关闭消息。CloseIntake收到它后 graceful complete 这个 Flow。