高级:多父 Flow 分区
查看 Markdown把请求分散到多个父 Flow ID,使正在运行的 SubFlow 总数可以超过单个父 Flow 的并发限制。
使用稳定的分区键,例如请求 ID 哈希对父 Flow 数量取模。相同键的请求始终到达同一个父 Flow。每个父 Flow 各自执行 Channel 缓冲区上限和 SubFlow 并发限制。增加父 Flow 就能提高总容量,单个 Flow 也不会无限增长。
改变父 Flow 的数量或顺序,会让一部分键落到别的父 Flow 上。如果扩容时每个键仍要落到同一个父 Flow,请使用带版本的父 Flow 集合或一致性哈希。
核心实现
SubmitStep 先调用目标父 Flow 的 RPC。如果父 Flow 不存在或已不在运行,SubmitStep 就以该请求作为初始输入启动它。父 Flow 的 Init 会把这个输入发布到 RequestChannel,所以请求不会丢失。如果另一个提交方抢先启动了父 Flow,本次启动会以 FlowAlreadyStarted 失败,SubmitStep 随后重试。下一次执行会在正在运行的父 Flow 上调用 RPC。
async def enqueue_request(client, parent_flow, parent_id: str, request: str) -> bool:
try:
return await client.invoke_rpc(parent_flow.send_request, parent_id, request)
except FlowNotActiveOrNotFoundError:
await client.start_flow(
parent_flow,
parent_id,
ParentInput([request], DEFAULT_CONCURRENCY),
StartFlowOptions(id_reuse_policy=IdReusePolicy.ALLOW_IF_NOT_RUNNING),
)
return True
def partition(request: str, partitions: int) -> int:
hash_value = 2_166_136_261
for byte in request.encode():
hash_value ^= byte
hash_value = hash_value * 16_777_619 & 0xFFFFFFFF
return hash_value % partitions
例子: examples/python/dex_examples/patterns/parallel-subflows/submit_request_flow.py
func enqueueRequest(ctx context.Context, client *dex.Client, parentFlow *AdvancedShortLiveParentFlow, parentID string, request string) (bool, error) {
accepted, err := invokeRequest(ctx, client, parentFlow, parentID, request)
if err == nil { return accepted, nil }
var inactive *dex.FlowNotActiveOrNotFoundError
if !errors.As(err, &inactive) { return false, err }
_, err = client.StartFlow(ctx, parentFlow, parentID, ParentInput{
Requests: []string{request}, Concurrency: DefaultConcurrency,
}, dex.StartFlowOptions{IDReusePolicy: dex.IDReuseAllowIfNotRunning})
if err != nil { return false, err }
return true, nil
}
func partition(request string, partitions int) int {
hash := uint32(2_166_136_261)
for _, value := range []byte(request) {
hash ^= uint32(value)
hash *= 16_777_619
}
return int(hash) % partitions
}
例子: examples/go/patterns/parallel-subflows/submit_request_flow.go
private boolean enqueueRequest(final String parentId, final String request) {
final Client client = clientProvider.getObject();
final AdvancedShortLiveParentFlow stub =
client.newRpcStub(AdvancedShortLiveParentFlow.class, parentId);
try {
return client.invokeRPC(stub::sendRequest, request);
} catch (final FlowNotActiveOrNotFoundException inactive) {
client.startFlow(
parentFlow,
parentId,
new ParentInput(new String[] {request}, AdvancedShortLiveParentFlow.DEFAULT_CONCURRENCY),
StartFlowOptions.newBuilder().idReusePolicy(IdReusePolicy.ALLOW_IF_NOT_RUNNING).build());
return true;
}
}
private static int partition(final String request, final int partitions) {
int hash = 0x811c9dc5;
for (final byte value : request.getBytes(StandardCharsets.UTF_8)) {
hash ^= Byte.toUnsignedInt(value);
hash *= 0x01000193;
}
return Integer.remainderUnsigned(hash, partitions);
}
例子: examples/java/src/main/java/io/superdurable/dex/patterns/parallelsubflows/SubmitRequestFlow.java
async function enqueueRequest(client: Client, parentFlow: AdvancedShortLiveParentFlow, parentId: string, request: string): Promise<boolean> {
try {
return await client.invokeRPC(parentFlow.sendRequest, parentId, request);
} catch (error) {
if (!isFlowMissingOrInactive(error)) throw error;
}
await client.startFlow(
parentFlow,
parentId,
{ requests: [request], concurrency: DEFAULT_CONCURRENCY },
{ idReusePolicy: IdReusePolicy.ALLOW_IF_NOT_RUNNING },
);
return true;
}
function partition(request: string, partitions: number): number {
let hash = 2_166_136_261;
for (const byte of new TextEncoder().encode(request)) {
hash ^= byte;
hash = Math.imul(hash, 16_777_619) >>> 0;
}
return hash % partitions;
}
例子: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
fn enqueue_request(client: &Client, parent_id: &str, request: String) -> HandlerResult<bool> {
match client.invoke_rpc(parent_id, SEND_SHORT_LIVE_REQUEST, request.clone()) {
Ok(accepted) => Ok(accepted),
Err(SdkError::FlowNotFound { .. } | SdkError::FlowNotActiveOrNotFound { .. }) => {
let parent = AdvancedShortLiveParentFlow::default();
let input = ParentInput { requests: vec![request.clone()], concurrency: DEFAULT_CONCURRENCY };
let options = StartFlowOptions::new().id_reuse_policy(IdReusePolicy::AllowIfNotRunning);
client.start_flow_with_options(&parent, parent_id, input, options).map_err(HandlerError::from_error)?;
Ok(true)
}
Err(error) => Err(HandlerError::from_error(error)),
}
}
fn partition(request: &str, partitions: usize) -> usize {
let mut hash = 2_166_136_261_u32;
for byte in request.bytes() {
hash ^= u32::from(byte);
hash = hash.wrapping_mul(16_777_619);
}
hash as usize % partitions
}