Skip to content

An open-source, faster Devin alternative

TypeScript

Address review: emit plan_changed after writes, dedupe webhook events, persist past-due

Mohamed Habib via Computer1271ce768f6e
diff --git a/cloudflare-workers/api-edge/migrations/0013_billing_webhook_state.sql b/cloudflare-workers/api-edge/migrations/0013_billing_webhook_state.sql
new file mode 100644
index 00000000..08fb2943
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/0013_billing_webhook_state.sql
@@ -0,0 +1,11 @@
+-- Billing webhook state (serverless-agents-ws 086, funnel events).
+-- orgs.payment_past_due_at: set when Autumn reports a subscription past due,
+-- cleared when it recovers or the org drops to no paid plan; a paid plan that
+-- ends while it is set lapsed rather than was cancelled.
+-- autumn_webhook_deliveries: Svix message ids whose funnel events were sent, so
+-- a redelivery does not count them twice.
+ALTER TABLE orgs ADD COLUMN payment_past_due_at INTEGER;
+CREATE TABLE IF NOT EXISTS autumn_webhook_deliveries (
+ svix_id TEXT PRIMARY KEY,
+ received_at INTEGER NOT NULL
+);
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
index 97e22825..186e0715 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
autumnPurchase,
+ autumnWebhook,
autumnSetAutoTopup,
autumnUsagePlanPurchase,
billingWebhookEvents,
@@ -8,6 +9,7 @@ import {
syncAutumnToD1,
summarizeAutumnCreditBalance,
type AutumnApiEnv,
+ type AutumnEnv,
} from "./autumn_webhook";
describe("Autumn credit balance summary", () => {
@@ -305,18 +307,33 @@ describe("billing funnel events from Autumn", () => {
expect(billingWebhookEvents({ type: "balances.limit_reached", data: {} })).toEqual([]);
});
- function planDb(usagePlan: string) {
- const org = { is_halted: 0, autumn_concurrency_override: null, usage_plan: usagePlan };
- return {
+ function fakeDb(usagePlan: string, pastDueAt: number | null = null) {
+ const org: Record<string, unknown> = {
+ is_halted: 0,
+ autumn_concurrency_override: null,
+ usage_plan: usagePlan,
+ payment_past_due_at: pastDueAt,
+ };
+ const deliveries = new Set<string>();
+ const db = {
+ org,
prepare(sql: string) {
return {
bind(...args: unknown[]) {
return {
- first: async () => ({ ...org }),
+ first: async () => (sql.includes("FROM sandboxes_index") ? null : { ...org }),
run: async () => {
- if (sql.includes("AND usage_plan = ?3")) {
+ if (sql.includes("INSERT OR IGNORE INTO autumn_webhook_deliveries")) {
+ if (deliveries.has(args[0] as string)) return { meta: { changes: 0 } };
+ deliveries.add(args[0] as string);
+ } else if (sql.includes("SET payment_past_due_at")) {
+ org.payment_past_due_at = args[0] ? (org.payment_past_due_at ?? args[1]) : null;
+ } else if (sql.includes("AND usage_plan = ?3")) {
if (org.usage_plan !== args[2]) return { meta: { changes: 0 } };
- org.usage_plan = args[0] as string;
+ org.usage_plan = args[0];
+ if (args[0] === "base") org.payment_past_due_at = null;
+ } else if (sql.includes("SET is_halted")) {
+ org.usage_plan = args[3];
}
return { meta: { changes: 1 } };
},
@@ -324,24 +341,29 @@ describe("billing funnel events from Autumn", () => {
},
};
},
- } as unknown as D1Database;
+ };
+ return db as typeof db & D1Database;
}
- it("emits plan_changed once when the projection moves the plan", async () => {
+ function mockAutumn(subscriptions: Array<{ plan_id: string }>) {
const posted: Array<Record<string, unknown>> = [];
vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
- const url = String(input);
- if (url.startsWith("https://autumn.test/v1/customers/")) {
+ if (String(input).startsWith("https://autumn.test/v1/customers/")) {
return Response.json({
id: "org_1",
- subscriptions: [{ plan_id: "pro", add_on: false, status: "active" }],
+ subscriptions: subscriptions.map((s) => ({ ...s, add_on: false, status: "active" })),
balances: { credits: { remaining: 10 } },
});
}
posted.push(JSON.parse(String(init?.body)));
return new Response(null, { status: 200 });
});
- const syncEnv = { ...env, OPENCOMPUTER_DB: planDb("base"), POSTHOG_PROJECT_TOKEN: "phc_test" };
+ return posted;
+ }
+
+ it("emits plan_changed once when the projection moves the plan", async () => {
+ const posted = mockAutumn([{ plan_id: "pro" }]);
+ const syncEnv = { ...env, OPENCOMPUTER_DB: fakeDb("base"), POSTHOG_PROJECT_TOKEN: "phc_test" };
expect((await syncAutumnToD1(syncEnv, "org_1"))?.usagePlan).toBe("pro");
await syncAutumnToD1(syncEnv, "org_1");
@@ -352,4 +374,65 @@ describe("billing funnel events from Autumn", () => {
properties: { from: "base", to: "pro", kind: "trial_converted" },
});
});
+
+ it("calls a plan that ends while past due lapsed, whoever projects it", async () => {
+ const posted = mockAutumn([]);
+ const db = fakeDb("pro", 1_700_000_000);
+
+ await syncAutumnToD1({ ...env, OPENCOMPUTER_DB: db, POSTHOG_PROJECT_TOKEN: "phc_test" }, "org_1");
+
+ expect(posted[0]).toMatchObject({ properties: { from: "pro", to: "base", kind: "lapsed" } });
+ expect(db.org.payment_past_due_at).toBeNull();
+ });
+
+ async function svixPost(webhookEnv: AutumnEnv, svixID: string, payload: unknown) {
+ const body = JSON.stringify(payload);
+ const ts = String(Math.floor(Date.now() / 1000));
+ const secret = btoa("webhook-key");
+ const key = await crypto.subtle.importKey(
+ "raw",
+ Uint8Array.from(atob(secret), (c) => c.charCodeAt(0)),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${svixID}.${ts}.${body}`)));
+ const sig = btoa(String.fromCharCode(...mac));
+ return autumnWebhook(
+ new Request("https://api.test/webhooks/autumn", {
+ method: "POST",
+ headers: { "svix-id": svixID, "svix-timestamp": ts, "svix-signature": `v1,${sig}` },
+ body,
+ }),
+ { ...webhookEnv, AUTUMN_WEBHOOK_SECRET: `whsec_${secret}` },
+ );
+ }
+
+ it("marks the org past due and sends a redelivered webhook's events once", async () => {
+ const posted = mockAutumn([{ plan_id: "pro" }]);
+ const db = fakeDb("pro");
+ const webhookEnv = {
+ ...env,
+ OPENCOMPUTER_DB: db,
+ POSTHOG_PROJECT_TOKEN: "phc_test",
+ EVENT_SECRET: "event-secret",
+ CF_ADMIN_SECRET: "admin-secret",
+ AUTUMN_WEBHOOK_SECRET: "",
+ } as unknown as AutumnEnv;
+ const payload = {
+ type: "billing.updated",
+ data: {
+ customer_id: "org_1",
+ plan_changes: [
+ { action: "updated", subscription: { plan_id: "pro", past_due: true }, previous_attributes: { past_due: false } },
+ ],
+ },
+ };
+
+ expect((await svixPost(webhookEnv, "msg_1", payload)).status).toBe(200);
+ expect((await svixPost(webhookEnv, "msg_1", payload)).status).toBe(200);
+
+ expect(db.org.payment_past_due_at).not.toBeNull();
+ expect(posted.map((p) => p.event)).toEqual(["billing.payment_failed"]);
+ });
});
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.ts
index f4248c94..c13ce164 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts
@@ -255,15 +255,18 @@ export async function autumnWebhook(
return json({ ok: true, ignored: type });
}
+ // Past-due state first, so a projection that ends the plan can tell a lapse
+ // from a cancel.
+ const pastDue = pastDueChanges(evt);
try {
- await projectOrg(env, orgID, { lapsed: subscriptionLapsed(evt) });
+ if (pastDue.length) await recordPastDue(env, orgID, pastDue[pastDue.length - 1].pastDue);
+ await projectOrg(env, orgID);
} catch (err) {
// 5xx → Svix retries with backoff (the Go reconciler is the longer backstop).
console.error(`autumn-webhook: project ${orgID} (${type}) failed`, err);
return json({ error: "projection failed" }, 502);
}
- // After the projection, so a 5xx retry does not count the event twice.
- for (const e of billingWebhookEvents(evt)) await emitBillingEvent(env, e.name, { orgId: orgID, data: e.data });
+ await emitWebhookEventsOnce(env, req.headers.get("svix-id"), orgID, billingWebhookEvents(evt));
await afterProject?.(orgID).catch((err) => console.error(`autumn-webhook: after-project ${orgID} (${type}) failed`, err));
return json({ ok: true, type, org_id: orgID });
}
@@ -284,11 +287,47 @@ interface AutumnWebhookPayload {
};
}
-// A subscription that expired while past due lapsed for non-payment; any other
-// expiry is a cancel. Only the webhook knows which, so it hints the projection.
-function subscriptionLapsed(evt: AutumnWebhookPayload): boolean {
- if (evt.type !== "billing.updated") return false;
- return (evt.data?.plan_changes ?? []).some((c) => c.action === "expired" && c.subscription?.past_due === true);
+// The subscriptions whose past_due flag flipped in a billing.updated webhook.
+function pastDueChanges(evt: AutumnWebhookPayload): Array<{ plan: string | null; pastDue: boolean }> {
+ if (evt.type !== "billing.updated") return [];
+ return (evt.data?.plan_changes ?? []).flatMap((c) => {
+ const was = c.previous_attributes?.past_due;
+ const now = c.subscription?.past_due;
+ if (was === undefined || now === undefined || was === now) return [];
+ return [{ plan: c.subscription?.plan_id ?? null, pastDue: now }];
+ });
+}
+
+async function recordPastDue(env: AutumnSyncEnv, orgID: string, pastDue: boolean): Promise<void> {
+ await env.OPENCOMPUTER_DB.prepare(
+ "UPDATE orgs SET payment_past_due_at = CASE WHEN ?1 THEN COALESCE(payment_past_due_at, ?2) ELSE NULL END WHERE id = ?3",
+ )
+ .bind(pastDue ? 1 : 0, Math.floor(Date.now() / 1000), orgID)
+ .run();
+}
+
+// Svix can deliver a message more than once, even after a 2xx, so a delivery's
+// events are sent only by the first one to record its svix-id. Sent after the
+// projection, so a 5xx retry still gets its turn.
+async function emitWebhookEventsOnce(
+ env: AutumnEnv,
+ svixID: string | null,
+ orgID: string,
+ events: ReturnType<typeof billingWebhookEvents>,
+): Promise<void> {
+ if (!events.length || !svixID) return;
+ try {
+ const first = await env.OPENCOMPUTER_DB.prepare(
+ "INSERT OR IGNORE INTO autumn_webhook_deliveries (svix_id, received_at) VALUES (?1, ?2)",
+ )
+ .bind(svixID, Math.floor(Date.now() / 1000))
+ .run();
+ if (first.meta?.changes !== 1) return;
+ } catch (err) {
+ console.error(`autumn-webhook: dedupe ${svixID} failed; events not sent`, err);
+ return;
+ }
+ for (const e of events) await emitBillingEvent(env, e.name, { orgId: orgID, data: e.data });
}
// billingWebhookEvents maps one Autumn webhook to its funnel events. Plan changes
@@ -305,17 +344,10 @@ export function billingWebhookEvents(
case "billing.auto_topup_failed":
return [{ name: "billing.payment_failed", data: { plan: "top_up", reason: d.reason ?? null } }];
case "billing.updated":
- return (d.plan_changes ?? []).flatMap((c) => {
- const was = c.previous_attributes?.past_due;
- const now = c.subscription?.past_due;
- if (was === undefined || now === undefined || was === now) return [];
- return [
- {
- name: now ? ("billing.payment_failed" as const) : ("billing.payment_recovered" as const),
- data: { plan: c.subscription?.plan_id ?? null },
- },
- ];
- });
+ return pastDueChanges(evt).map((c) => ({
+ name: c.pastDue ? ("billing.payment_failed" as const) : ("billing.payment_recovered" as const),
+ data: { plan: c.plan },
+ }));
default:
return [];
}
@@ -323,6 +355,7 @@ export function billingWebhookEvents(
// planChangeKind names a usage-plan transition for billing.plan_changed. `base`
// is "no paid plan" (the trial, or a pre-launch free org) until step 5 names it.
+// A paid plan that ends while past due (orgs.payment_past_due_at) lapsed.
export function planChangeKind(from: UsagePlan, to: UsagePlan, lapsed: boolean): string {
if (from === "base") return "trial_converted";
if (to === "base") return lapsed ? "lapsed" : "cancel";
@@ -608,11 +641,7 @@ export interface AutumnSyncResult {
usagePlan: UsagePlan;
}
-export async function syncAutumnToD1(
- env: AutumnSyncEnv,
- orgID: string,
- opts: { lapsed?: boolean } = {},
-): Promise<AutumnSyncResult | null> {
+export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise<AutumnSyncResult | null> {
const cust = await getAutumnCustomer(env, orgID);
if (!cust) {
console.error(`autumn: customer ${orgID} not found in Autumn`);
@@ -626,25 +655,33 @@ export async function syncAutumnToD1(
const nowSec = Math.floor(Date.now() / 1000);
const prevRow = await env.OPENCOMPUTER_DB.prepare(
- "SELECT is_halted, autumn_concurrency_override, usage_plan FROM orgs WHERE id = ?1",
+ "SELECT is_halted, autumn_concurrency_override, usage_plan, payment_past_due_at FROM orgs WHERE id = ?1",
)
.bind(orgID)
- .first<{ is_halted: number; autumn_concurrency_override: number | null; usage_plan: UsagePlan }>();
+ .first<{
+ is_halted: number;
+ autumn_concurrency_override: number | null;
+ usage_plan: UsagePlan;
+ payment_past_due_at: number | null;
+ }>();
const wasHalted = prevRow?.is_halted === 1;
const maxConcurrent = prevRow?.autumn_concurrency_override ?? projectedMaxConcurrent;
// Compare-and-set the plan first: the webhook, checkout-return and the cron can
// project the same change concurrently, and only the writer that moves it emits.
+ // Dropping to no paid plan clears the past-due mark once it has been read.
const fromPlan = prevRow?.usage_plan;
+ let planChange: Record<string, string> | null = null;
if (fromPlan && fromPlan !== usagePlan) {
- const moved = await env.OPENCOMPUTER_DB.prepare("UPDATE orgs SET usage_plan = ?1 WHERE id = ?2 AND usage_plan = ?3")
+ const moved = await env.OPENCOMPUTER_DB.prepare(
+ `UPDATE orgs SET usage_plan = ?1, payment_past_due_at = CASE WHEN ?1 = 'base' THEN NULL ELSE payment_past_due_at END
+ WHERE id = ?2 AND usage_plan = ?3`,
+ )
.bind(usagePlan, orgID, fromPlan)
.run();
if (moved.meta?.changes === 1) {
- await emitBillingEvent(env, "billing.plan_changed", {
- orgId: orgID,
- data: { from: fromPlan, to: usagePlan, kind: planChangeKind(fromPlan, usagePlan, opts.lapsed === true) },
- });
+ const lapsed = prevRow?.payment_past_due_at != null;
+ planChange = { from: fromPlan, to: usagePlan, kind: planChangeKind(fromPlan, usagePlan, lapsed) };
}
}
@@ -654,6 +691,10 @@ export async function syncAutumnToD1(
.bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, usagePlan, nowSec, orgID)
.run();
+ // After the writes, so the event's send time never widens the window in which
+ // a concurrent projection can interleave.
+ if (planChange) await emitBillingEvent(env, "billing.plan_changed", { orgId: orgID, data: planChange });
+
return { customer: cust, creditsRemaining, maxConcurrent, halted, wasHalted, usagePlan };
}
@@ -701,8 +742,8 @@ export async function autumnSetProviderInternal(req: Request, env: AutumnEnv): P
// do NOT dispatch — D1.is_halted is already cleared, which unblocks the gates;
// hibernated boxes wake lazily on the next request. This is the locked "no
// auto-wake for prepaid" decision: a top-up unblocks but never force-wakes.
-export async function projectOrg(env: AutumnEnv, orgID: string, opts: { lapsed?: boolean } = {}): Promise<void> {
- const r = await syncAutumnToD1(env, orgID, opts);
+export async function projectOrg(env: AutumnEnv, orgID: string): Promise<void> {
+ const r = await syncAutumnToD1(env, orgID);
if (!r || !r.halted) return;
// Dispatch halt on the fresh transition, OR whenever a halted org STILL has
// running sandboxes — so a halt is eventually complete even if a single