有业务标识的子 Flow
查看 Markdown当每个子任务都有自己的业务编号时,使用这个模式。人和其他系统用这个编号查找、重试或停止子任务。
例如,一个订单分成几个包裹发货。每个发货单有一个发货单号。承运商、客服团队和订单都用这个单号找到发货单。订单仍然需要知道每个发货单最后的结果。
订单把每个发货单作为独立的顶层 Flow 启动。发货单号就是它的 Flow ID。
工作方式
StartShipments为每个发货单启动一个分支。StartShipment通过 Client 启动一个ShipmentFlow。它的 Flow ID 是发货单号。发货单有自己的 Flow timeout。StartShipment把启动返回的 run ID 交给下一个 Step。ClaimShipment把这个 run ID 记录为被认领的 run。它还会合并在认领之前到达的报告。- 发货单送达。
DeliverShipment把结果存进shipmentOutcomeAttribute。 ReportShipmentOutcome带着自己的 run ID 调用订单的报告 RPC。这个 RPC 在 Go 里是RecordShipmentOutcome,在 Python 里是record_shipment_outcome,在 Java、TypeScript 和 Rust 里是recordShipmentOutcome。它把结果填进该发货单的记录。AwaitShipment每隔一段时间读取一次这个 run。仍在运行的发货单稍后再读。发货单关闭后,RecordShipmentEnd记录终止状态;如果报告还没有填入结果,它也记录读到的结果。
报告 RPC 和写这些记录的 Step 共用一把锁。RPC 从不等锁:Step 持有锁时,RPC 直接失败。Step 的锁在它的重试和退避期间一直持有。所以调用 Client 的 Step,也就是 StartShipment 和 AwaitShipment,不拿锁。它们各自把结果交给一个只写记录的短小加锁 Step。
自己失败或超时的发货单不会报告,因为它的报告 Step 不会运行。第 6 步的定时读取会处理它。子 Flow 也可以把最终失败转到一个恢复 Step,或把超时交给 timeout handler,由它们向父 Flow 报告。每个发货单的 Flow timeout 要长于它的重试预算。
示例处理的边界情况见生产检查清单。
# dex:group group-id:start group-label:"Start shipments"
# dex:explanation text:"Starts the shipment as a top-level Flow named by its shipment number."
class StartShipment(Step[TrackedShipment]):
"""Starts ShipmentFlow with the shipment number as its Flow ID.
It takes no lock: a report must never wait for the start call or its retries.
"""
def __init__(
self,
client_provider: Callable[[], AsyncClient],
shipment_flow: ShipmentFlow,
) -> None:
self.client_provider = client_provider
self.shipment_flow = shipment_flow
async def execute( # type: ignore[override]
self, context: AsyncContext, tracked: TrackedShipment
) -> StepDecision:
number = tracked.shipment.shipment_number
try:
run_id = await self.client_provider().start_flow(
self.shipment_flow,
number,
ShipmentRequest(order_flow_id=context.flow_id, shipment=tracked.shipment),
StartFlowOptions(
timeout=SHIPMENT_TIMEOUT,
id_reuse_policy=IdReusePolicy.DISALLOW,
request_id=shipment_start_request_id(context.flow_id, tracked.shipment),
ignore_already_started=True,
例子: examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py
// dex:group group-id:start group-label:"Start shipments"
// dex:explanation text:"Starts the shipment as a top-level Flow named by its shipment number."
type StartShipment struct {
dex.StepDefaultsNoWaitFor[TrackedShipment]
getClient func() *dex.Client
shipmentFlow *ShipmentFlow
}
// Execute takes no lock: a report must never wait for the start call or its retries.
func (step StartShipment) Execute(ctx dex.Context, tracked TrackedShipment) (*dex.StepDecision, error) {
client := step.getClient()
if client == nil {
return nil, errClientUnavailable
}
number := tracked.Shipment.ShipmentNumber
requestID, err := ShipmentStartRequestID(ctx.FlowID(), tracked.Shipment)
if err != nil {
return nil, err
}
timeout := ShipmentTimeout
runID, err := client.StartFlow(ctx, step.shipmentFlow, number, ShipmentRequest{
OrderFlowID: ctx.FlowID(),
Shipment: tracked.Shipment,
}, dex.StartFlowOptions{
Timeout: &timeout,
IDReusePolicy: dex.IDReuseDisallow,
RequestID: &requestID,
AlreadyStarted: &dex.AlreadyStartedOptions{IgnoreError: true},
})
var alreadyStarted *dex.FlowAlreadyStartedError
例子: examples/go/patterns/child-flows-business-identity/order_fulfillment_flow.go
// dex:group group-id:start group-label:"Start shipments"
// dex:explanation text:"Starts the shipment as a top-level Flow named by its shipment number."
static final class StartShipment implements Step<TrackedShipment> {
private final ObjectProvider<Client> clientProvider;
private final ShipmentFlow shipmentFlow;
StartShipment(final ObjectProvider<Client> clientProvider, final ShipmentFlow shipmentFlow) {
this.clientProvider = clientProvider;
this.shipmentFlow = shipmentFlow;
}
@Override
public Class<TrackedShipment> getInputType() {
return TrackedShipment.class;
}
/** Takes no lock: a report must never wait for the start call or its retries. */
@Override
public StepDecision execute(final Context context, final TrackedShipment tracked) {
final Client client = clientProvider.getObject();
final String number = tracked.shipment().shipmentNumber();
final String requestId = shipmentStartRequestId(context.getFlowId(), tracked.shipment());
final String runId;
try {
runId = client.startFlow(
shipmentFlow,
number,
new ShipmentRequest(context.getFlowId(), tracked.shipment()),
StartFlowOptions.newBuilder()
.timeout(SHIPMENT_TIMEOUT)
// dex:group group-id:start group-label:"Start shipments"
// dex:explanation text:"Starts the shipment as a top-level Flow named by its shipment number."
class StartShipment implements Step<TrackedShipment> {
public constructor(
private readonly getClient: () => Client,
private readonly shipmentFlow: ShipmentFlow,
) {}
public getStepType(): string {
return "StartShipment";
}
/** Takes no lock: a report must never wait for the start call or its retries. */
public async execute(context: Context, tracked: TrackedShipment): Promise<StepDecision> {
// Calling a field through this would hide the Step class from the Flow visualizer.
const getClient = this.getClient;
const number = tracked.shipment.shipmentNumber;
const requestId = shipmentStartRequestId(context.flowId, tracked.shipment);
let runId: string;
try {
runId = await getClient().startFlow(
this.shipmentFlow,
number,
{ orderFlowId: context.flowId, shipment: tracked.shipment },
{
timeoutMs: SHIPMENT_TIMEOUT_MS,
idReusePolicy: IdReusePolicy.DISALLOW,
requestId,
ignoreAlreadyStarted: true,
},
例子: examples/typescript/src/patterns/child-flows-business-identity/order-fulfillment-flow.ts
// dex:group group-id:start group-label:"Start shipments"
// dex:explanation text:"Starts the shipment as a top-level Flow named by its shipment number."
#[derive(Default)]
struct StartShipment {
client: Option<Arc<Client>>,
}
impl Step for StartShipment {
type Input = TrackedShipment;
/// Takes no lock: a report must never wait for the start call or its retries.
fn execute(
&self,
context: &mut Context,
mut tracked: Self::Input,
) -> HandlerResult<StepDecision> {
let client = require_client(self.client.as_ref())?;
let order_flow_id = context.flow_id().to_string();
let number = tracked.shipment.shipment_number.clone();
let request_id = shipment_start_request_id(&order_flow_id, &tracked.shipment);
let request = ShipmentRequest {
order_flow_id,
shipment: tracked.shipment.clone(),
};
let options = StartFlowOptions::new()
.timeout(SHIPMENT_TIMEOUT)
.id_reuse_policy(IdReusePolicy::Disallow)
.request_id(request_id)
.ignore_already_started(true);
match client.start_flow_with_options(&ShipmentFlow::default(), &number, request, options) {
例子: examples/rust/src/control_patterns/child_flows_business_identity/order_fulfillment_flow.rs
结果提交后再报告
发货单在一个 Step 里提交结果,在下一个 Step 里报告。两个 Step 都为 Execute 显式声明 SYNC durability。这样即使 Flow 默认是 ASYNC,报告 Step 也只会在结果存好之后开始。
报告带上发货单自己的 run ID。Client 支持 RPC request ID 时,报告还带有稳定的 request ID:report:、发货单号、: 和 run ID。
订单已经关闭时,报告会返回带类型的错误。发货单到此结束尝试。它的结果仍然可以通过 Client 读取。
# dex:group group-id:deliver group-label:"Deliver"
# dex:explanation text:"Waits for the carrier, then commits the delivered outcome."
class DeliverShipment(Step[ShipmentRequest]):
"""Waits for the simulated carrier, then stores the outcome."""
def get_step_options(self) -> StepOptions:
"""Stores the outcome before the report Step starts, even when the Flow defaults to ASYNC."""
return StepOptions(execute_durability=StepDurability.SYNC)
def wait_for(self, context: Context, request: ShipmentRequest) -> Wait:
return Wait.until(
Timer.by_duration(timedelta(seconds=request.shipment.delivery_delay_seconds))
)
def execute(self, context: Context, request: ShipmentRequest) -> StepDecision:
outcome = "delivered to " + request.shipment.destination
SHIPMENT_OUTCOME.set(context, outcome)
return go_to(
ReportShipmentOutcome,
PendingReport(
order_flow_id=request.order_flow_id,
report=ShipmentReport(
shipment_number=request.shipment.shipment_number,
shipment_run_id=context.run_id,
outcome=outcome,
),
),
)
例子: examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py
// dex:group group-id:deliver group-label:"Deliver"
// dex:explanation text:"Waits for the carrier, then commits the delivered outcome."
type DeliverShipment struct{ dex.StepDefaults }
// GetStepOptions stores the outcome before the report Step starts, even when the Flow defaults to ASYNC.
func (DeliverShipment) GetStepOptions() *dex.StepOptions {
return &dex.StepOptions{ExecuteDurability: dex.StepDurabilitySync}
}
func (DeliverShipment) WaitFor(_ dex.Context, request ShipmentRequest) (*dex.Wait, error) {
return dex.Until(dex.Timer(time.Duration(request.Shipment.DeliveryDelaySeconds) * time.Second)), nil
}
func (DeliverShipment) Execute(ctx dex.Context, request ShipmentRequest) (*dex.StepDecision, error) {
outcome := "delivered to " + request.Shipment.Destination
if err := ShipmentOutcome.Set(ctx, outcome); err != nil {
return nil, err
}
return dex.GoTo(ReportShipmentOutcome{}, PendingReport{
OrderFlowID: request.OrderFlowID,
Report: ShipmentReport{
ShipmentNumber: request.Shipment.ShipmentNumber,
ShipmentRunID: ctx.RunID(),
Outcome: outcome,
},
}), nil
}
// PendingReport is the report a shipment still has to send to its order.
type PendingReport struct {
例子: examples/go/patterns/child-flows-business-identity/order_fulfillment_flow.go
// dex:group group-id:deliver group-label:"Deliver"
// dex:explanation text:"Waits for the carrier, then commits the delivered outcome."
static final class DeliverShipment implements Step<ShipmentRequest> {
@Override
public Class<ShipmentRequest> getInputType() {
return ShipmentRequest.class;
}
/**
* Stores the outcome before the report Step starts, even when the Flow defaults to ASYNC.
*/
@Override
public StepOptions getStepOptions() {
return StepOptions.newBuilder().executeDurability(StepDurability.SYNC).build();
}
@Override
public Wait waitFor(final Context context, final ShipmentRequest request) {
return Wait.until(Timer.byDuration(
Duration.ofSeconds(request.shipment().deliveryDelaySeconds())));
}
@Override
public StepDecision execute(final Context context, final ShipmentRequest request) {
final String outcome = "delivered to " + request.shipment().destination();
shipmentOutcome.set(context, outcome);
return StepDecision.goTo(ReportShipmentOutcome.class, new PendingReport(
request.orderFlowId(),
new ShipmentReport(
request.shipment().shipmentNumber(), context.getRunId(), outcome)));
// dex:group group-id:deliver group-label:"Deliver"
// dex:explanation text:"Waits for the carrier, then commits the delivered outcome."
class DeliverShipment implements Step<ShipmentRequest> {
public getStepType(): string {
return "DeliverShipment";
}
/** Stores the outcome before the report Step starts, even when the Flow defaults to ASYNC. */
public getStepOptions(): StepOptions {
return { executeDurability: "sync" };
}
public waitFor(_context: Context, request: ShipmentRequest): Wait {
return Wait.until(Timer.byDuration(request.shipment.deliveryDelaySeconds * 1000));
}
public execute(context: Context, request: ShipmentRequest): StepDecision {
const outcome = `delivered to ${request.shipment.destination}`;
shipmentOutcome.set(context, outcome);
const pending: PendingReport = {
orderFlowId: request.orderFlowId,
report: { shipmentNumber: request.shipment.shipmentNumber, shipmentRunId: context.runId, outcome },
};
return goTo(ReportShipmentOutcome, pending);
}
}
// dex:group group-id:report group-label:"Report"
// dex:explanation text:"Reports the committed outcome to the order that started this shipment."
class ReportShipmentOutcome implements Step<PendingReport> {
例子: examples/typescript/src/patterns/child-flows-business-identity/shipment-flow.ts
// dex:group group-id:deliver group-label:"Deliver"
// dex:explanation text:"Waits for the carrier, then commits the delivered outcome."
#[derive(Default)]
struct DeliverShipment;
impl Step for DeliverShipment {
type Input = ShipmentRequest;
/// Stores the outcome before the report Step starts, even when the Flow defaults to ASYNC.
fn options(&self) -> StepOptions<Self::Input> {
StepOptions::new().execute_durability(StepDurability::Sync)
}
fn wait_for(&self, _context: &mut Context, request: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::until(Timer::by_duration(duration_from_seconds(
request.shipment.delivery_delay_seconds,
))))
}
fn execute(&self, context: &mut Context, request: Self::Input) -> HandlerResult<StepDecision> {
let outcome = format!("delivered to {}", request.shipment.destination);
SHIPMENT_OUTCOME.set(context, outcome.clone())?;
Ok(StepDecision::go_to(
&ReportShipmentOutcome::default(),
PendingReport {
order_flow_id: request.order_flow_id,
report: ShipmentReport {
shipment_number: request.shipment.shipment_number,
shipment_run_id: context.run_id().to_string(),
outcome,
例子: examples/rust/src/control_patterns/child_flows_business_identity/shipment_flow.rs
每个发货单一条记录
订单在 shipmentRecords AttributeMap 里为每个发货单保存一条记录,以发货单号为键。记录把状态、被认领的 run ID 和结果分成三个字段。
报告 RPC 把结果填进发货单的记录。报告可能在 ClaimShipment 记录 run 之前到达。这时 RPC 把它存进 pendingShipmentReports AttributeMap,以发货单号为键。每一项保存每个 run ID 的第一份报告。ClaimShipment 合并被认领 run 的报告。它接受哪些报告,见生产检查清单。
@rpc(
lock_attributes=(SHIPMENT_RECORDS_LOCK.lock(),),
load_attribute_maps=(SHIPMENT_RECORDS, PENDING_SHIPMENT_REPORTS),
)
def record_shipment_outcome(self, context: Context, report: ShipmentReport) -> None:
"""Fills the outcome of a shipment's record.
It accepts only the run this order claimed. The first report wins, and
any other report changes nothing. Before the claim, it keeps the first
report of each run for ClaimShipment to merge.
"""
record, found = load_shipment_record(context, report.shipment_number)
# Ignore an unknown shipment and a report without a run.
if not found or not report.shipment_run_id:
return
if record.status == SHIPMENT_STARTING:
pending: dict[str, ShipmentReport] = (
PENDING_SHIPMENT_REPORTS.get(context, report.shipment_number) or {}
)
if report.shipment_run_id not in pending:
PENDING_SHIPMENT_REPORTS.set(
context,
report.shipment_number,
{**pending, report.shipment_run_id: report},
)
return
# Ignore a rejected shipment, another run, and a repeated report.
if (
not record.run_id
or record.run_id != report.shipment_run_id
or record.outcome
):
return
SHIPMENT_RECORDS.set(
context,
report.shipment_number,
dataclasses.replace(record, outcome=report.outcome),
)
例子: examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py
func (flow *OrderFulfillmentFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.RecordShipmentOutcome, &dex.RPCOptions{
LockAttributes: []dex.AttributeLock{dex.LockAttribute(ShipmentRecordsLock)},
LoadAttributeMaps: []dex.AttributeDef{ShipmentRecords, PendingShipmentReports},
}),
dex.DefineRPC(flow.GetDexSummary, &dex.RPCOptions{LoadAttributeMaps: []dex.AttributeDef{ShipmentRecords}}),
dex.DefineRPC(flow.GetDexDisplay, &dex.RPCOptions{LoadAttributeMaps: []dex.AttributeDef{ShipmentRecords}}),
}
}
// RecordShipmentOutcome fills the outcome of a shipment's record. It accepts only the run
// this order claimed; the first report wins, and any other report changes nothing.
// Before the claim, it keeps the first report of each run for ClaimShipment to merge.
// It returns an error only when the records cannot be read or written.
func (*OrderFulfillmentFlow) RecordShipmentOutcome(ctx dex.Context, report ShipmentReport) (*dex.RPCResult[dex.None], error) {
record, found, err := loadShipmentRecord(ctx, report.ShipmentNumber)
if err != nil {
return nil, err
}
// Ignore an unknown shipment and a report without a run.
if !found || report.ShipmentRunID == "" {
return &dex.RPCResult[dex.None]{}, nil
}
if record.Status == ShipmentStarting {
if err := keepPendingReport(ctx, report); err != nil {
return nil, err
}
return &dex.RPCResult[dex.None]{}, nil
}
例子: examples/go/patterns/child-flows-business-identity/order_fulfillment_flow.go
/**
* Fills the outcome of a shipment's record. It accepts only the run this order claimed; the
* first report wins, and any other report changes nothing. Before the claim, it keeps the
* first report of each run for {@link ClaimShipment} to merge.
*
* @param context the RPC context
* @param report the shipment run's report
*/
@RPC(
lockAttributes = {"shipmentRecordsLock"},
loadAttributeMaps = {"shipmentRecords", "pendingShipmentReports"})
public void recordShipmentOutcome(final Context context, final ShipmentReport report) {
final Optional<ShipmentRecord> found = loadShipmentRecord(context, report.shipmentNumber());
// Ignore an unknown shipment and a report without a run.
if (found.isEmpty() || report.shipmentRunId() == null || report.shipmentRunId().isEmpty()) {
return;
}
if (SHIPMENT_STARTING.equals(found.get().status())) {
final PendingShipmentReports stored =
pendingShipmentReports.get(context, report.shipmentNumber());
final PendingShipmentReports pending =
stored != null ? stored : new PendingShipmentReports();
if (pending.putIfAbsent(report.shipmentRunId(), report) == null) {
pendingShipmentReports.set(context, report.shipmentNumber(), pending);
}
return;
}
// Ignore a rejected shipment, another run, and a repeated report.
if (found.get().runId() == null
|| !found.get().runId().equals(report.shipmentRunId())
|| found.get().outcome() != null) {
return;
}
final ShipmentRecord record = found.get();
shipmentRecords.set(context, report.shipmentNumber(),
new ShipmentRecord(record.status(), record.runId(), report.outcome()));
}
/**
* Fills the outcome of a shipment's record. It accepts only the run this
* order claimed; the first report wins, and any other report changes nothing.
* Before the claim, it keeps the first report of each run for ClaimShipment
* to merge.
*/
@rpc({
lockAttributes: [shipmentRecordsLock.lock()],
loadAttributeMaps: [shipmentRecords, pendingShipmentReports],
})
public recordShipmentOutcome(context: Context, report: ShipmentReport): void {
const { record, found } = loadShipmentRecord(context, report.shipmentNumber);
// Ignore an unknown shipment and a report without a run.
if (!found || report.shipmentRunId === "") {
return;
}
if (record.status === SHIPMENT_STARTING) {
const pending = loadPendingReports(context, report.shipmentNumber) ?? {};
if (!Object.hasOwn(pending, report.shipmentRunId)) {
pendingShipmentReports.set(context, report.shipmentNumber, {
...pending,
[report.shipmentRunId]: report,
});
}
return;
}
// Ignore a rejected shipment, another run, and a repeated report.
if (
record.runId === undefined ||
record.runId !== report.shipmentRunId ||
record.outcome !== undefined
) {
return;
}
shipmentRecords.set(context, report.shipmentNumber, { ...record, outcome: report.outcome });
}
例子: examples/typescript/src/patterns/child-flows-business-identity/order-fulfillment-flow.ts
/// Fills the outcome of a shipment's record. It accepts only the run this
/// order claimed; the first report wins, and any other report changes nothing.
/// Before the claim, it keeps the first report of each run for
/// `ClaimShipment` to merge.
///
/// Returns an error only when the records cannot be read or written.
fn record_shipment_outcome(
&self,
context: &mut Context,
report: ShipmentReport,
) -> HandlerResult<()> {
// Ignore an unknown shipment and a report without a run.
let Some(mut record) = load_shipment_record(context, &report.shipment_number)? else {
return Ok(());
};
if report.shipment_run_id.is_empty() {
return Ok(());
}
if record.status.as_deref() == Some(SHIPMENT_STARTING) {
let mut pending = PENDING_SHIPMENT_REPORTS
.get(context, &report.shipment_number)?
.unwrap_or_default();
if !pending.contains_key(&report.shipment_run_id) {
let number = report.shipment_number.clone();
pending.insert(report.shipment_run_id.clone(), report);
PENDING_SHIPMENT_REPORTS.set(context, &number, pending)?;
}
return Ok(());
}
// Ignore a rejected shipment, another run, and a repeated report.
if record.run_id.as_deref() != Some(report.shipment_run_id.as_str())
|| record.outcome.is_some()
{
return Ok(());
}
record.outcome = Some(report.outcome);
SHIPMENT_RECORDS.set(context, &report.shipment_number, record)
}
fn rpcs(&self) -> RpcList<Self> {
RpcList::new().procedure(
RECORD_SHIPMENT_OUTCOME
.lock(SHIPMENT_RECORDS_LOCK.lock())
.load_attribute_map(&SHIPMENT_RECORDS)
.load_attribute_map(&PENDING_SHIPMENT_REPORTS),
Self::record_shipment_outcome,
)
}
例子: examples/rust/src/control_patterns/child_flows_business_identity/order_fulfillment_flow.rs
AwaitShipment 每隔一段时间描述一次发货单。仍在运行的发货单在下一个间隔再读,即使它的报告已经到达。发货单关闭后,RecordShipmentEnd 记录它的状态;报告还没有填入结果时,也记录结果。
客服团队可以按单号取消发货单。在结果提交之前被取消的发货单没有结果,订单把它记录为 canceled。在结果提交之后、或在报告发出之后被取消的发货单仍可能有结果,订单会保留它。
按单号查找发货单
任何调用方都可以按单号找到发货单,不需要知道订单。示例的 HTTP 路由先描述这个 ID 对应的 Flow。它不是 ShipmentFlow 时返回 404,所以订单 ID 不能被当作发货单读取或取消。
async def describe_shipment(number: str) -> FlowInfo | None:
"""Describes the Flow named by a shipment number.
Returns None when no ShipmentFlow has that Flow ID. Any other failure raises.
"""
try:
info = await app_state.client.describe_flow(number)
except FlowNotFoundError:
return None
return info if info.flow_type == SHIPMENT_FLOW_TYPE else None
@blueprint.get("/shipment")
async def get_shipment() -> tuple[dict[str, str], int]:
"""Looks a shipment up by its shipment number, which is its Flow ID."""
number = required_query("shipmentNumber")
info = await describe_shipment(number)
if info is None:
return {"error": f"shipment {number} not found"}, 404
values = await app_state.client.get_attributes(number, SHIPMENT_OUTCOME)
return {
"shipmentNumber": number,
"status": info.status.value,
"outcome": values.get(SHIPMENT_OUTCOME, ""),
}, 200
@blueprint.get("/cancel-shipment")
async def cancel_shipment() -> tuple[str | dict[str, str], int]:
"""Stops a shipment by its number. Its order records it at the next reconcile read."""
number = required_query("shipmentNumber")
if await describe_shipment(number) is None:
return {"error": f"shipment {number} not found"}, 404
await app_state.client.stop_flow(
number,
StopFlowOptions(type=StopType.CANCEL, reason="shipment canceled"),
)
return "canceled", 200
例子: examples/python/dex_examples/patterns/child-flows-business-identity/controller.py
// getShipment looks a shipment up by its shipment number, which is its Flow ID.
func (controller *controller) getShipment(request *gin.Context) {
number, info, found := controller.describeShipment(request)
if !found {
return
}
var outcome string
_, err := controller.client.GetAttributes(request.Request.Context(), number,
dex.ReadAttribute(ShipmentOutcome, &outcome))
httputil.Respond(request, gin.H{
"shipmentNumber": number,
"status": info.Status.String(),
"outcome": outcome,
}, err)
}
// cancelShipment stops a shipment by its number. Its order records it at the next reconcile read.
func (controller *controller) cancelShipment(request *gin.Context) {
number, _, found := controller.describeShipment(request)
if !found {
return
}
err := controller.client.StopFlow(request.Request.Context(), number, dex.StopOptions{
Type: dex.CancelFlow,
Reason: "shipment canceled",
})
httputil.RespondString(request, "canceled", err)
}
// describeShipment describes the Flow named by the shipmentNumber query.
// It returns found as false after it responded: 404 when no ShipmentFlow has that Flow ID.
func (controller *controller) describeShipment(request *gin.Context) (string, dex.FlowInfo, bool) {
number, found := httputil.RequiredQuery(request, "shipmentNumber")
if !found {
return "", dex.FlowInfo{}, false
}
info, err := controller.client.DescribeFlow(request.Request.Context(), number)
var notFound *dex.FlowNotFoundError
if errors.As(err, ¬Found) || (err == nil && info.FlowType != shipmentFlowType) {
request.JSON(http.StatusNotFound, gin.H{"error": "shipment " + number + " not found"})
return "", dex.FlowInfo{}, false
}
if err != nil {
httputil.Respond(request, nil, err)
return "", dex.FlowInfo{}, false
}
return number, info, true
}
例子: examples/go/patterns/child-flows-business-identity/controller.go
/** Looks a shipment up by its shipment number, which is its Flow ID. */
@GetMapping("/shipment")
ResponseEntity<?> getShipment(@RequestParam final String shipmentNumber) {
final Optional<FlowInfo> found = describeShipment(shipmentNumber);
if (found.isEmpty()) {
return shipmentNotFound(shipmentNumber);
}
final FlowInfo info = found.get();
final String outcome = client.getAttributes(shipmentNumber, ShipmentFlow.shipmentOutcome)
.get(ShipmentFlow.shipmentOutcome)
.orElse("");
final Map<String, String> response = new LinkedHashMap<String, String>();
response.put("shipmentNumber", shipmentNumber);
response.put("status", OrderFulfillmentFlow.statusName(info.getStatus()));
response.put("outcome", outcome);
return ResponseEntity.ok(response);
}
/** Stops a shipment by its number. Its order records it at the next reconcile read. */
@GetMapping("/cancel-shipment")
ResponseEntity<?> cancelShipment(@RequestParam final String shipmentNumber) {
if (describeShipment(shipmentNumber).isEmpty()) {
return shipmentNotFound(shipmentNumber);
}
client.stopFlow(shipmentNumber, new StopFlowOptions(StopType.CANCEL, "shipment canceled"));
return ResponseEntity.ok("canceled");
}
/**
* Describes the Flow named by a shipment number.
*
* @param shipmentNumber the shipment number, which is the shipment's Flow ID
* @return the shipment's Flow info, or empty when no ShipmentFlow has that Flow ID
*/
private Optional<FlowInfo> describeShipment(final String shipmentNumber) {
try {
final FlowInfo info = client.describeFlow(shipmentNumber);
if (!OrderFulfillmentFlow.SHIPMENT_FLOW_TYPE.equals(info.getFlowType())) {
return Optional.empty();
}
return Optional.of(info);
} catch (final FlowNotFoundException notFound) {
return Optional.empty();
}
}
private static ResponseEntity<Map<String, String>> shipmentNotFound(final String shipmentNumber) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", "shipment " + shipmentNumber + " not found"));
}
// Looks a shipment up by its shipment number, which is its Flow ID.
router.get("/shipment", async (request, response) => {
const shipment = await describeShipment(client, request, response);
if (shipment === undefined) {
return;
}
const [outcome] = await client.getAttributes(shipment.flowId, shipmentOutcome);
response.json({
shipmentNumber: shipment.flowId,
status: shipmentStatusOf(shipment.status),
outcome: outcome ?? "",
});
});
// Stops a shipment by its number. Its order records it at the next reconcile read.
router.get("/cancel-shipment", async (request, response) => {
const shipment = await describeShipment(client, request, response);
if (shipment === undefined) {
return;
}
await client.stopFlow(shipment.flowId, { type: StopType.CANCEL, reason: "shipment canceled" });
response.send("canceled");
});
/**
* Describes the Flow named by the shipmentNumber query.
*
* @returns The shipment's FlowInfo, or undefined after it responded: 404 when
* no ShipmentFlow has that Flow ID.
*/
例子: examples/typescript/src/patterns/child-flows-business-identity/controller.ts
/// Looks a shipment up by its shipment number, which is its Flow ID.
async fn get_shipment(
State(client): State<SharedClient>,
Query(query): Query<ShipmentQuery>,
) -> Response {
let (number, info) = match describe_shipment(&client, query).await {
Ok(described) => described,
Err(response) => return response,
};
let lookup_number = number.clone();
let lookup = run_blocking(move || client.get_attributes(&lookup_number, (&*SHIPMENT_OUTCOME,)));
match lookup {
Ok((outcome,)) => ok_json(ShipmentView {
shipment_number: number,
status: flow_status_name(info.status).to_string(),
outcome: outcome.unwrap_or_default(),
}),
Err(error) => map_sdk_error(error).into_response(),
}
}
/// Stops a shipment by its number. Its order records it at the next reconcile read.
async fn cancel_shipment(
State(client): State<SharedClient>,
Query(query): Query<ShipmentQuery>,
) -> Response {
let (number, _info) = match describe_shipment(&client, query).await {
Ok(described) => described,
Err(response) => return response,
};
例子: examples/rust/src/control_patterns/child_flows_business_identity/controller.rs
可以在 examples playground 里试用这些路由。发货单字段默认是当前订单的第二个发货单。
选择这个模式还是 SubFlow
子任务只为父 Flow 存在时,选择 SubFlow。Dex 从父 Flow 派生它的 Flow ID,父 Flow 用 Condition 等待它。
子任务需要自己的标识时,选择顶层子 Flow:
- 人或系统按它自己的编号查找、重试或停止它。
- 父 Flow 之外的调用方也可以启动它。
- 它可以比父 Flow 活得更久,有自己的 Flow timeout。
代价是更多代码。父 Flow 要启动子 Flow、认领它的 run、接收它的报告,并一直读取它,直到它结束。
生产检查清单
- 认领子 run。 启动返回后,
ClaimShipment记录 run ID。从这以后,订单只接受这个 run 的报告和读取。订单先把每个单号登记为starting。所有写这些记录的地方都锁住单例 AttributeshipmentRecordsLock:StartShipments、ClaimShipment、RecordShipmentEnd和报告 RPC。这个锁 Attribute 不存任何值,只让写入方一次一个地修改记录。 - 加锁的 Step 里不调用 Client。
StartShipment和AwaitShipment调用 Client,不拿锁。报告遇到锁时会返回锁冲突错误,发货单会重试它。加锁的 Step 不做任何调用,所以只短暂持有锁。 - 只接受被认领的 run 发来的报告。 状态仍是
starting的发货单还没有被认领的 run。RPC 在pendingShipmentReports里按发货单号保存每个 run 的第一份报告。用别的单号发来的报告不会把它挡掉。ClaimShipment合并被认领 run 的报告,再删除这个发货单的整项,所以结果只计一次。拒绝时也会删除这一项。未知或rejected的单号、来自其他 run 的报告、或者记录里已经有结果时,报告都不会改变什么。其余情况下,RPC 填入结果。 - 先读结果,再确认 run。
AwaitShipment调用reconcileShipment(Python 和 Rust 里是reconcile_shipment)。它的第一次 Describe 只在找不到 Flow,或 run ID 与被认领的不同时,才记录unavailable。读到终止状态后,它读结果 Attribute。Attribute 未设置表示发货单结束时没有结果。Attribute 读取返回 FlowNotFound 时,函数保留这个状态,并跳过第二次 Describe。Attribute 读取看到的是发货单最新的 run。读取成功时,函数再描述一次发货单,检查 run ID。run 已消失或被取代时,函数保留状态,丢弃这次读取的结果。订单已经收到的报告仍保留在记录里。 - 其他读取错误会重试。 其他错误让
AwaitShipment这个 Step 失败,Dex 会重试它。重试期间不持有锁,所以报告仍能到达。 - 考虑发货单号以后被重新使用。 找不到发货单,或者同一单号的另一个 run 取代了被认领的 run 时,订单记录
unavailable。这是业务策略。订单运行期间,只要被认领的 run 仍是发货单最新的 run,订单就能知道它的终止状态。其他调用方重新使用这个单号,或者这个 run 的数据被删除之后,订单就读不到它了。一个发货单号只属于一个订单。另一个请求已经用过这个单号时,启动会返回带类型的 already-started 错误。示例把这个发货单记录为rejected,并忽略发给它的报告。订单从不等待、计数或停止被拒绝的发货单,因为那个 run 属于另一个请求。每次业务尝试都使用自己的发货单号。 - 拒绝同一订单里的重复单号。
StartShipments在启动任何发货单之前先检查订单:对账间隔为正数,送达延迟不是负数,发货单号都不重复。 - 对启动请求做摘要。 启动的 request ID 是完整启动请求的摘要。只要原来的 run 仍是发货单最新的 run,重试的 Step 重复的就是同一次启动。如果其他调用方在认领之前重新使用了这个单号,重试会收到 already-started 错误,订单记录
rejected。要保护尚未认领的启动,所有启动发货单的入口都必须禁止 ID 复用。