An open-source, faster Devin alternative
TypeScript
billing clock: take least recently updated orgs first
Mohamed Habib via Computer2e871c16e023
diff --git a/cloudflare-workers/api-edge/src/billing_clock.test.ts b/cloudflare-workers/api-edge/src/billing_clock.test.tsindex 4ee304eb..c0dd80b4 100644--- a/cloudflare-workers/api-edge/src/billing_clock.test.ts+++ b/cloudflare-workers/api-edge/src/billing_clock.test.ts@@ -8,10 +8,12 @@ describe("billing clock", () => {it("re-projects orgs whose trial or payment grace has run out", async () => {const project = vi.spyOn(autumn, "projectOrg").mockResolvedValue();let bound: unknown[] = [];+ let sql = "";const env = {OPENCOMPUTER_DB: {- prepare: () => ({+ prepare: (q: string) => ({bind: (...args: unknown[]) => {+ sql = q;bound = args;return { all: async () => ({ results: [{ id: "org_a" }, { id: "org_b" }] }) };},@@ -20,6 +22,8 @@ describe("billing clock", () => {} as unknown as autumn.AutumnEnv;expect(await runBillingClock(env, 1_800_000_000_000)).toBe(2);+ // Least recently updated first, so orgs that stay unhalted can't fill every batch.+ expect(sql).toMatch(/ORDER BY updated_at\s+LIMIT/);expect(bound).toEqual([1_800_000_000 - 7 * 86_400, 1_800_000_000 - 3 * 86_400, 50]);expect(project.mock.calls.map((c) => c[1])).toEqual(["org_a", "org_b"]);});diff --git a/cloudflare-workers/api-edge/src/billing_clock.ts b/cloudflare-workers/api-edge/src/billing_clock.tsindex 9df17588..9b6747af 100644--- a/cloudflare-workers/api-edge/src/billing_clock.ts+++ b/cloudflare-workers/api-edge/src/billing_clock.ts@@ -2,8 +2,10 @@// time passing rather than usage. A trial ends on day 7 and a failing payment// halts after its grace even when the org does nothing, so the */5 cron// re-projects the orgs whose clock has run out; projectOrg decides and halts.-// A halted or paid-up org no longer matches, so each org is projected about-// once per transition.+// A halted or paid-up org no longer matches. One that matches but stays+// unhalted (a credit-only signup before the Autumn trial plan exists) is+// re-projected every tick, so the batch takes the least recently updated rows+// first: projectOrg stamps updated_at, and such rows cannot starve the rest.import { type AutumnEnv, PAYMENT_GRACE_DAYS, TRIAL_DAYS, projectOrg } from "./autumn_webhook";@@ -17,6 +19,7 @@ export async function runBillingClock(env: AutumnEnv, nowMs: number): Promise<nu`SELECT id FROM orgsWHERE billing_provider = 'autumn' AND is_halted = 0AND ((usage_plan = 'base' AND trial_started_at <= ?1) OR payment_past_due_at <= ?2)+ ORDER BY updated_atLIMIT ?3`,).bind(nowSec - TRIAL_DAYS * DAY_SEC, nowSec - PAYMENT_GRACE_DAYS * DAY_SEC, MAX_ORGS_PER_RUN)