Child Flows with Business Identity
View as MarkdownUse this pattern when each child job has its own business number. People and other systems look the child up, retry it, or stop it by that number.
An example is an order that ships as several parcels. Each shipment has a shipment number. The carrier, the support team, and the order all find the shipment by that number. The order still needs to know how each shipment ended.
The order starts each shipment as its own top-level Flow. The shipment number is its Flow ID.
How it works
StartShipmentsstarts one branch per shipment.StartShipmentstarts aShipmentFlowthrough the Client. Its Flow ID is the shipment number. The shipment gets its own Flow timeout.StartShipmentpasses the run ID that the start returns to the next Step.ClaimShipmentrecords that run ID as the claimed run. It also merges a report that arrived before the claim.- The shipment delivers.
DeliverShipmentstores its outcome in theshipmentOutcomeAttribute. ReportShipmentOutcomecalls the order's report RPC with its own run ID. The RPC isRecordShipmentOutcomein Go,record_shipment_outcomein Python, andrecordShipmentOutcomein Java, TypeScript, and Rust. It fills the outcome in the shipment's record.AwaitShipmentreads that run at each interval. A running shipment is read again later. For a closed shipment,RecordShipmentEndrecords the terminal status, and the read outcome when no report filled it.
The report RPC and the Steps that write the records share one lock. An RPC never waits for a lock: it fails while a Step holds it. A Step's lock stays held through its retries and backoff. So the Steps that call the Client, StartShipment and AwaitShipment, take no lock. Each hands its result to a short locked Step that only writes the records.
A shipment that fails or times out on its own never reports, because its report Step never runs. The interval read in step 6 covers it. A child can also route its terminal failure to a recovery Step, or its timeout to a timeout handler, that reports to the parent. Keep each shipment's Flow timeout longer than its retry budget.
The Production checklist covers the edge cases the example handles.
# 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,
Example: 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
Example: 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,
},
Example: 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) {
Example: examples/rust/src/control_patterns/child_flows_business_identity/order_fulfillment_flow.rs
Report after the outcome commits
The shipment commits its outcome in one Step and reports in the next. Both Steps declare SYNC durability for Execute. The report Step then starts only after the outcome is stored, even when the Flow defaults to ASYNC.
The report carries the shipment's own run ID. When the Client accepts an RPC request ID, the report also carries a stable one: report:, the shipment number, :, and the run ID.
When the order has already closed, the report fails with a typed error. The shipment ends its attempts there. Its outcome stays readable through the 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,
),
),
)
Example: 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 {
Example: 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> {
Example: 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,
Example: examples/rust/src/control_patterns/child_flows_business_identity/shipment_flow.rs
One record per shipment
The order keeps one record per shipment in the shipmentRecords AttributeMap, keyed by the shipment number. The record holds the status, the claimed run ID, and the outcome as separate fields.
The report RPC fills the outcome in the shipment's record. A report can arrive before ClaimShipment records the run. The RPC then keeps it in the pendingShipmentReports AttributeMap, keyed by the shipment number. Each entry holds the first report of each run ID. ClaimShipment merges the claimed run's report. The Production checklist lists which reports it accepts.
@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),
)
Example: 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
}
Example: 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 });
}
Example: 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,
)
}
Example: examples/rust/src/control_patterns/child_flows_business_identity/order_fulfillment_flow.rs
AwaitShipment describes the shipment at each interval. A running shipment is read again at the next interval, even after its report arrived. For a closed shipment, RecordShipmentEnd records its status, and its outcome when no report filled it.
The support team can cancel a shipment by its number. A shipment canceled before its outcome commits has no outcome; the order records it as canceled. A shipment canceled after its outcome commits, or after it sent its report, can still have an outcome, and the order keeps it.
Look up a shipment by its number
Any caller can find a shipment by its number, without knowing the order. The example's HTTP routes describe the Flow with that ID first. A Flow that is not a ShipmentFlow answers 404, so an order ID cannot be read or canceled as a shipment.
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
Example: 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
}
Example: 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.
*/
Example: 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,
};
Example: examples/rust/src/control_patterns/child_flows_business_identity/controller.rs
Try the routes in the examples playground. Its shipment fields default to the second shipment of the current order.
Choose this or a SubFlow
Choose a SubFlow when the child exists only for its parent. Dex derives its Flow ID from the parent, and the parent waits for it with a Condition.
Choose a top-level child Flow when the child needs its own identity:
- People or systems look it up, retry it, or stop it by its own number.
- Something other than the parent can start it.
- It can outlive the parent, with its own Flow timeout.
The cost is more code. The parent starts the child, claims its run, receives its report, and reads it until it ends.
Production checklist
- Claim the child run. After the start returns,
ClaimShipmentrecords the run ID. From then on, the order accepts reports and reads of that run only. The order first registers each number asstarting. Every writer of the records locks the singletonshipmentRecordsLockAttribute:StartShipments,ClaimShipment,RecordShipmentEnd, and the report RPC. The lock Attribute stores no value; it lets one writer at a time change the records. - Keep Client calls out of locked Steps.
StartShipmentandAwaitShipmentcall the Client and take no lock. A report that meets the lock fails with a lock conflict, and the shipment retries it. The locked Steps make no calls, so they hold the lock only briefly. - Accept reports only from the claimed run. A shipment that is still
startinghas no claimed run yet. The RPC keeps the first report of each run under the shipment number inpendingShipmentReports. A report sent under another number never hides it.ClaimShipmentmerges the claimed run's report, then deletes the shipment's whole entry, so the outcome is counted once. A rejection deletes the entry too. A report for an unknown orrejectednumber, from another run, or for a record that already has an outcome changes nothing. Otherwise the RPC fills the outcome. - Read the result, then confirm the run.
AwaitShipmentcallsreconcileShipment(reconcile_shipmentin Python and Rust). Its first Describe recordsunavailableonly when the Flow is not found or its run ID differs from the claimed one. After it reads a terminal status, it reads the outcome Attribute. An unset Attribute means the shipment ended without an outcome. When the Attribute read returns FlowNotFound, the function keeps the status and skips the second Describe. The Attribute read sees the shipment's latest run. When it succeeds, the function describes the shipment again to check the run ID. When the run is gone or replaced, the function keeps the status and drops this read's outcome. Reports the order already received stay in the record. - Retry other read errors. Any other error fails the
AwaitShipmentStep, so Dex retries it. The retries hold no lock, so reports still arrive. - Plan for a shipment number reused later. When the shipment cannot be found, or another run of the same number replaced the claimed one, the order records
unavailable. That is a business policy. The order learns the terminal status of a claimed run while the order runs and the run stays the shipment's latest run. Once another caller reopens the number, or the run's data is deleted, the order can no longer read it. A shipment number belongs to one order. When another request already used the number, the start fails with a typed already-started error. The example records that shipment asrejectedand ignores reports for it. The order never waits for, counts, or stops a rejected shipment, because that run belongs to another request. Give each business attempt its own shipment number. - Reject duplicate numbers in one order.
StartShipmentschecks the order before it starts anything: the reconcile interval is positive, no delivery delay is negative, and every shipment number is unique. - Hash the start request. The request ID of the start is a digest of the complete start request. A retried Step repeats the same start while the original run is still the shipment's latest run. When another caller reopens the number before the claim, the retry gets the already-started error, and the order records
rejected. To protect unclaimed starts, every entry point that starts a shipment must disallow ID reuse.