跳到主要内容

订单处理

查看 Markdown

向买家扣款,等卖家批准发货,然后发货。发货一直失败时,给买家退款。

SDK: Python · Go · TypeScript · Java · Rust

展示:提醒、Execute 失败恢复和等待 Step 完成。

Flow 设计

  • Charge 向买家扣款,并把 order-status Attribute 设为 charged。
  • Ship 等待 seller-ok Channel 上的卖家批准,或一个 24 小时的 Timer。Timer 先触发时,Ship 发一封提醒,然后再等一轮。批准之后,它发货,把 order-status 设为 shipped,并以输出 shipped:<订单 ID> 完成 Flow。
  • Refund 在 Ship 的重试用完后运行。它给买家退款,把 order-status 设为 refunded,并以 refunded:<订单 ID> 完成 Flow。图中 Step 上的 ⚠ 表示一条失败路由;选中这个 Step 可以看到它通向哪里。

approve RPC 把批准消息发到 seller-ok。describe RPC 返回 order-status。

核心实现

扣款、发货和退款调用都带上用订单 ID 构造的幂等键,订单 ID 也就是 Flow ID:charge-<订单 ID>、ship-<订单 ID> 和 refund-<订单 ID>。被中断的 Step 可能带着同一个键再次运行,所以支付和发货服务可以丢弃重复的调用。见 幂等键。真实的提醒邮件也需要幂等键,因为被中断的 Step 可能再次运行。示例没有传。

每个 Step 的 Execute 有 3 秒的重试预算,让演示很快结束;代码注释建议生产环境用一小时。Ship 的失败路由转到 Refund,Refund 有自己的短重试。

Flow 通过 constructor 拿到服务(Flow 包含什么)。order-status 建了索引,所以可以按状态搜索 Flow。dex:group 和 dex:explanation 注释标注上图中的各个 Step。

order_processing_flow.pyPython
order_status = Attribute(
"order-status",
str,
AttributeIndex(IndexType.KEYWORD, "keyword1"),
)
seller_ok = Channel[str]("seller-ok", str)


# dex:group group-id:payment group-label:"Payment"
# dex:explanation text:"Charge the customer for the order."
class Charge(Step[OrderRequest]):
def __init__(self, service: MyDependencyService) -> None:
self.service = service

def get_step_options(self) -> StepOptions:

def execute(self, context: Context, input: OrderRequest) -> StepDecision:
self.service.charge_user(
input.email,
input.customer_id,
input.amount,
idempotency_key=f"charge-{input.order_id}",
)
order_status.set(context, "charged")
return go_to(Ship, input)


# dex:group group-id:shipping group-label:"Shipping"
# dex:explanation text:"Wait for seller approval, remind after 24 hours, then ship the order."
class Ship(Step[OrderRequest]):
def __init__(self, service: MyDependencyService) -> None:
self.service = service

def get_step_options(self) -> StepOptions:

def wait_for(self, context: Context, input: OrderRequest) -> Wait:
return Wait.any_of(
seller_ok.for_one(),
Timer.by_duration(timedelta(hours=24)),
)

def execute(self, context: Context, input: OrderRequest) -> StepDecision:
if context.has_timer_fired():
self.service.send_email(
input.email,
"Reminder: approve shipment",
"Please approve or provide a tracking number.",
)
return go_to(Ship, input)
self.service.ship_item(
input.order_id,
input.test_fail_at_shipping,
idempotency_key=f"ship-{input.order_id}",
)
order_status.set(context, "shipped")
return graceful_complete(f"shipped:{input.order_id}")


# dex:group group-id:refund group-label:"Refund"
# dex:explanation text:"Refund the order when shipping keeps failing."
class Refund(Step[OrderRequest]):
def __init__(self, service: MyDependencyService) -> None:
self.service = service

def execute(self, context: Context, input: OrderRequest) -> StepDecision:
self.service.update_external_system(
f"refund {input.order_id}", idempotency_key=f"refund-{input.order_id}"
)
order_status.set(context, "refunded")
return graceful_complete(f"refunded:{input.order_id}")


class OrderProcessingFlow(Flow[OrderRequest]):
def __init__(self, service: MyDependencyService) -> None:
self.service = service
self.refund = Refund(service)
self.ship = Ship(service)
self.charge = Charge(service)

def get_steps(self) -> StepList[OrderRequest]:
return StepList.start_step(self.charge).other_steps(self.ship, self.refund)

def get_persistence_schema(self) -> PersistenceSchema:
return PersistenceSchema.of(order_status, seller_ok)

@rpc
def approve(self, context: Context, _note: str) -> RPCResult[str]:
seller_ok.publish(context, "approved")
return RPCResult("ok")

@rpc
def describe(self, context: Context) -> RPCResult[str]:
return RPCResult(order_status.get(context))

例子: examples/python/dex_examples/products/order-processing/order_processing_flow.py

HTTP 处理器

示例应用在同一个进程里运行 Worker 和这些 handler。start 启动 Flow,用 Client 的 wait-for-Step-completion API 等 Charge 完成后才返回。approve 和 describe 调用同名的 RPC。

controller.pyPython
    @blueprint.get("/start")
async def start() -> Response:
flow_id = new_flow_id("order-processing")
request = OrderRequest(
flow_id,
"buyer@example.com",
"customer-1",
42,
optional_query("testFailAtShipping", "") == "true",
)
run_id = await app_state.client.start_flow(
app_state.order_processing,
flow_id,
request,
start_options(),
)
await app_state.client.wait_for_step_completion(
flow_id,
CHARGE_STEP,
WaitForStepCompletionOptions(),
)
return started_flow(flow_id, run_id)

@blueprint.get("/approve")
async def approve() -> Response:
output = await app_state.client.invoke_rpc(
app_state.order_processing.approve,
_required_flow_id(),
optional_query("notes", ""),
)
return jsonify(output)

@blueprint.get("/describe")
async def describe() -> Response:
flow_id = _required_flow_id()
status = await app_state.client.invoke_rpc(
app_state.order_processing.describe,
flow_id,
)
return jsonify({"flowID": flow_id, "status": status})

return blueprint


def _required_flow_id() -> str:
"""Reads the Flow ID from flowId, or from its alias workflowId."""
return optional_query("workflowId", "") or required_query("flowId")

例子: examples/python/dex_examples/products/order-processing/controller.py

运行

按在 playground 里运行一个示例启动一种语言的示例。然后创建一个订单:

curl -s 'http://127.0.0.1:8080/products/order-processing/start'

从响应里复制 flowID。在 Dex Web(dexcli dev 打印的地址,例如 http://127.0.0.1:8802)里,这条 Flow 停在 Ship 等待。把 FLOW_ID 换成它,批准发货:

curl -s "http://127.0.0.1:8080/products/order-processing/approve?flowId=FLOW_ID"

这个调用把批准消息发到 seller-ok。随后 Ship 发货,Flow 完成;可以在 Dex Web 里看到这个过程。也可以在 examples playground 里选择 Order processing,做同样的调用。

试试退款路径

创建一个发货总会失败的订单:

curl -s 'http://127.0.0.1:8080/products/order-processing/start?testFailAtShipping=true'

复制新的 flowID,像上面一样批准它。随后 Ship 一直失败,直到 3 秒的重试预算用完,然后 Refund 运行。在 Dex Web 里等到 Refund 完成,或者重复下面的调用,直到状态变成 refunded:

curl -s "http://127.0.0.1:8080/products/order-processing/describe?flowId=FLOW_ID"

在 Dex Web 的 Events 下,Graph 显示 Charge、Ship,然后是 Refund。

在 Dex Web 中查看运行

打开一次已批准的运行,选择 Events。Timeline 按顺序显示扣款、批准和发货;选中一个事件可以读取它的输入和输出。Graph 显示各 Step 如何衔接。

Dex Web Timeline 展示订单从扣款、批准到发货的过程

Dex Web Graph 展示订单从扣款、批准到发货的过程

下一步