订阅与计费生命周期
查看 Markdown让订阅经历试用期、各个计费周期、价格调整和取消。Flow 在持久的 Timer 和 Channel 上等待,所以一个订阅可以运行几个月。
SDK: Python · Go · TypeScript · Java · Rust
图和下面的说明对应 Python、Go、Java 和 TypeScript 示例。Rust 示例有所不同。
产品需求
订阅计划规定试用时长、计费周期时长、计费周期数和扣费金额。订阅必须:
- 发送欢迎邮件,试用期结束前不扣费。
- 每个计费周期扣费一次。最后一个周期结束后,通知客户并结束。
- 随时接受新的扣费金额。Flow 应用它之后开始的扣费使用新金额。
- 随时接受取消:通知客户并结束订阅。
- 通过
describeRPC 返回订阅计划。
Flow 设计
Initialize 把客户和计费周期计数器存进 Attribute,然后启动三个分支。Trial 发送欢迎邮件并等待试用期 Timer。随后 ChargeCurrentBill 循环运行:它的 WaitFor 把周期数加一并等待本周期的 Timer,它的 Execute 扣费后回到 ChargeCurrentBill。最后一个周期结束后,它通知客户并强制完成 Flow。Cancel 等待一条取消消息,通知客户并强制完成 Flow。UpdateChargeAmount 每次应用一个新金额,然后回到自身。
这个设计有两个关键选择:
- 每个分支都从 Attribute 读取客户和计划。更新金额的 RPC 只把新金额放进队列,由 UpdateChargeAmount 写入。在这个 Step 提交之后才开始的计费 Execute 会读到新金额。已经在运行的扣费仍用旧金额,重试时也一样。
- 强制完成 Flow 时,其他分支的等待也随之结束,不需要哪个分支去停止其他分支。
取消可能在一次扣费进行中到达。Cancel 会结束 Flow,但已经发给支付提供方的扣费仍可能完成。这种情况由你的退款和权益策略决定。
真实的支付调用需要幂等键,因为被中断的 Step 可能再次运行。示例没有传。合适的键是 Flow ID 加计费周期数。WaitFor 在 Execute 扣费之前提交这个周期数,所以同一次扣费的每次重试都发送相同的键,提供方可以丢弃重复的请求。欢迎、结束和取消邮件也各需要自己的键,例如 Flow ID 加邮件用途。
核心实现
每个标签页展示可运行示例中的 Flow 类。上面的图来自 Python 的 Flow;Go、TypeScript 和 Java 的 Step 相同。
class SubscriptionFlow(Flow[Customer]):
billing_period_number = Attribute("billing-period-number", int)
customer_details = Attribute("customer", Customer)
cancel_subscription = Channel[None]("cancel-subscription", type(None))
update_charge_amount = Channel("update-charge-amount", int)
def __init__(self, service: MyDependencyService) -> None:
self.service = service
self.charge_current_bill = ChargeCurrentBill(
service,
self.customer_details,
self.billing_period_number,
)
self.trial = Trial(
service,
self.customer_details,
self.billing_period_number,
self.charge_current_bill,
)
self.cancel = Cancel(
service,
self.customer_details,
self.cancel_subscription,
)
self.update_charge_amount_step = UpdateChargeAmount(
self.customer_details,
self.update_charge_amount,
)
self.initialize = Initialize(
self.customer_details,
例子: examples/python/dex_examples/products/subscription/subscription_flow.py
type SubscriptionFlow struct {
dex.FlowDefaults
service service.MyService
}
func NewSubscriptionFlow(applicationService service.MyService) *SubscriptionFlow {
return &SubscriptionFlow{service: applicationService}
}
func (flow *SubscriptionFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(initializeStep{}),
dex.DefineStep(trial{service: flow.service}),
dex.DefineStep(chargeCurrentBill{service: flow.service}),
dex.DefineStep(cancelStep{service: flow.service}),
dex.DefineStep(updateChargeAmountStep{}),
}
}
func (flow *SubscriptionFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.Describe, nil),
dex.DefineRPC(flow.GetCustomer, nil),
dex.DefineRPC(flow.Cancel, nil),
dex.DefineRPC(flow.UpdateCharge, nil),
}
}
func (*SubscriptionFlow) GetPersistenceSchema() dex.PersistenceSchema {
return dex.PersistenceSchema{
Attributes: []dex.AttributeDef{BillingPeriodNumber, CustomerDetails},
Channels: []dex.ChannelDef{CancelSubscription, UpdateChargeAmount},
}
}
func (*SubscriptionFlow) Describe(
ctx dex.Context,
_ dex.None,
) (*dex.RPCResult[Subscription], error) {
customer, err := CustomerDetails.Get(ctx)
if err != nil {
return nil, err
}
return &dex.RPCResult[Subscription]{Output: customer.Subscription}, nil
}
@Component
public class SubscriptionFlow implements Flow<Customer> {
private static final String SUBSCRIPTION_OVER_KEY = "subscription-over";
public final Attribute<Integer> billingPeriodNumber =
Attribute.define("billing-period-number", Integer.class);
public final Attribute<Customer> customerDetails =
Attribute.define("customer", Customer.class);
public final Channel<Void> cancelSubscription =
Channel.define("cancel-subscription", Void.class);
public final Channel<Integer> updateChargeAmount =
Channel.define("update-charge-amount", Integer.class);
private final MyDependencyService service;
private final Initialize initialize = new Initialize();
private final Trial trial = new Trial();
private final ChargeCurrentBill chargeCurrentBill = new ChargeCurrentBill();
private final Cancel cancel = new Cancel();
private final UpdateChargeAmount updateChargeAmountStep = new UpdateChargeAmount();
public SubscriptionFlow(final MyDependencyService service) {
this.service = service;
}
@Override
public StepList<Customer> getSteps() {
return StepList.startStep(initialize)
.otherSteps(trial, chargeCurrentBill, cancel, updateChargeAmountStep);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(
billingPeriodNumber,
customerDetails,
cancelSubscription,
updateChargeAmount);
}
@RPC
public RPCResult<Subscription> describe(final Context context) {
return RPCResult.of(customerDetails.get(context).subscription);
}
例子: examples/java/src/main/java/io/superdurable/dex/products/subscription/SubscriptionFlow.java
export class SubscriptionFlow implements Flow<Customer> {
public readonly billingPeriodNumber = new Attribute("billing-period-number", doubleCodec);
public readonly customerDetails = new Attribute("customer", customerCodec);
public readonly initialize = new Initialize(this);
public readonly trial = new Trial(this);
public readonly chargeCurrentBill = new ChargeCurrentBill(this);
public readonly cancel = new Cancel(this);
public readonly updateChargeAmountStep = new UpdateChargeAmount(this);
public constructor(public readonly service: MyDependencyService = myDependencyService) {}
public getFlowType(): string {
return "SubscriptionFlow";
}
public getSteps() {
return StepList.startStep(this.initialize).otherSteps(
this.trial,
this.chargeCurrentBill,
this.cancel,
this.updateChargeAmountStep,
);
}
public getPersistenceSchema(): PersistenceSchema {
return {
attributes: [this.billingPeriodNumber, this.customerDetails],
channels: [cancelSubscription, updateChargeAmount],
};
}
@rpc()
public describe(context: Context): RPCResult<Subscription> {
return { output: this.customerDetails.get(context).subscription };
}
例子: examples/typescript/src/products/subscription/subscription-flow.ts
#[derive(Default)]
pub struct SubscriptionFlow {
welcome: Welcome,
billing: Billing,
control: Control,
}
impl SubscriptionFlow {
fn describe(&self, context: &mut Context) -> HandlerResult<RpcResult<SubscriptionState>> {
Ok(RpcResult::new(STATE.get(context)?.unwrap_or_default()))
}
fn update_charge(&self, context: &mut Context, amount: i64) -> HandlerResult<()> {
COMMANDS.publish(context, SubscriptionCommand::Charge(amount))
}
fn cancel(&self, context: &mut Context) -> HandlerResult<()> {
COMMANDS.publish(context, SubscriptionCommand::Cancel)
}
}
impl Flow for SubscriptionFlow {
type StartInput = SubscriptionRequest;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.welcome)
.and(&self.billing)
.and(&self.control)
}
fn persistence(&self) -> PersistenceSchema {
PersistenceSchema::new()
.attribute(&STATE)
.channel(&COMMANDS)
}
fn rpcs(&self) -> RpcList<Self> {
RpcList::new()
.function_without_input(DESCRIBE_SUBSCRIPTION, Self::describe)
.procedure(UPDATE_SUBSCRIPTION_CHARGE, Self::update_charge)
.procedure_without_input(CANCEL_SUBSCRIPTION, Self::cancel)
}
}
Rust 示例
Rust 示例更小,不调用任何服务。Welcome 保存订阅状态并记录一条欢迎事件,没有试用期。然后它启动两个分支。Billing 等待一天的 Timer,然后把已扣费周期数加一。Control 每次从一个命令 Channel 取一条消息,更新金额和取消的 RPC 都发布到这个 Channel。它把新金额或取消写进状态,取消时强制完成 Flow。最后一个周期之后,Billing 请求优雅完成,而优雅完成要等 Control 结束,所以这次运行只会因取消而结束。两个 Step 都在不加锁的情况下读写整个状态,所以一方可能覆盖另一方的改动。
在 playground 中,Start 创建一个三个周期、每期 1000 cents 的计划。调用 Update charge amount,然后用返回的 Flow ID 反复调用 Describe,直到它显示新金额。Describe 返回金额、已扣费周期数和取消标志。Cancel 结束这次运行。
运行
按在 playground 里运行一个示例启动一种语言的示例。然后在 examples playground 中打开 Subscription:
- Start 返回新的 Flow ID。它启动 20 秒的试用期和十个 10 秒的计费周期,每期扣费 100。
- 用这个 Flow ID 调用 Update charge amount,新金额进入队列。反复调用 Describe,直到它显示新金额;此后开始的扣费使用它。
- Cancel 把取消放进队列,随后 Cancel Step 结束订阅。
在 Dex Web 中打开这次运行的 Events。Timeline 显示价格更新和取消。Graph 显示取消结束 Flow 时,哪些 Step 已完成、哪些仍在等待。

