import { beforeEach, describe, expect, test } from "bun:test"; import { meterDef } from "~/lib/meters"; import type { MeterId } from "~/lib/meters"; const { accountSql, fakeEnv, quantity, resetMeteringHarness, recordUsage, claimScratchUsage, MeteringError, reserveUsage, commitUsage, releaseUsage, assertWithinQuota, QuotaExceededError, setPlan, clearPlanOverride, setSpendingLimit, withinSpendingLimit, billingSettings, scratchSiteAccount, countingBody, } = await import("./metering.test-helper"); beforeEach(() => resetMeteringHarness()); describe("hardening", () => { test("a scratch account cannot be claimed by a second account", async () => { const scratch = scratchSiteAccount("s2"); await claimScratchUsage(scratch, "u1"); await expect(claimScratchUsage(scratch, "u2")).rejects.toBeInstanceOf(MeteringError); }); test("claiming carries in-flight holds so later releases don't undercount", async () => { const scratch = scratchSiteAccount("s3"); const hold = await reserveUsage({ id: "h1", accountId: scratch, meter: "compute.site_requests", quantity: 5 }); await claimScratchUsage(scratch, "u1"); await releaseUsage(hold.id, scratch); const row = accountSql("u1") .query("SELECT reserved FROM usage_periods WHERE account_id = 'u1' AND meter = 'compute.site_requests'") .get(); expect(row).toEqual({ reserved: 0 }); }); test("the spending limit caps total overage across meters", async () => { await setPlan("u1", "pro", "billing"); await setSpendingLimit("u1", 1); expect(await withinSpendingLimit("u1")).toBe(true); await recordUsage({ accountId: "u1", meter: "ai.calls", quantity: 1000 + 20, idempotencyKey: "over" }); expect(await withinSpendingLimit("u1")).toBe(false); expect(await withinSpendingLimit("u1", "ops.git_ops")).toBe(true); await expect(assertWithinQuota("u1", "compute.runner")).rejects.toBeInstanceOf(QuotaExceededError); }); test("concurrent holds on different meters share one spending limit (BILL-P1)", async () => { await setPlan("u1", "pro", "billing"); await setSpendingLimit("u1", 10); const pro = (await billingSettings("u1")).plan; const unitsFor = (meter: MeterId, cents: number) => (pro.included[meter] ?? 0) + (cents * 1e6) / (meterDef(meter)?.microCentsPerUnit ?? 1); await reserveUsage({ id: "a", accountId: "u1", meter: "ai.calls", quantity: unitsFor("ai.calls", 7) }); const refused = await reserveUsage({ id: "b", accountId: "u1", meter: "compute.editor", quantity: unitsFor("compute.editor", 6), }).catch((error: unknown) => error); expect(refused).toBeInstanceOf(QuotaExceededError); expect((refused as InstanceType).reason).toBe("spending_limit"); const fits = await reserveUsage({ id: "c", accountId: "u1", meter: "compute.editor", quantity: unitsFor("compute.editor", 2), }); expect(fits.id).toBe("c"); }); test("an admin-pinned plan survives billing updates until it is handed back (BILL-P8)", async () => { await setPlan("u1", "pro", "admin"); await setPlan("u1", "free", "billing"); expect((await billingSettings("u1")).plan.id).toBe("pro"); await clearPlanOverride("u1"); await setPlan("u1", "free", "billing"); expect((await billingSettings("u1")).plan.id).toBe("free"); }); test("follow billing applies the stored subscription and only trusts the Pro price", async () => { const { followBillingPlan } = await import("../billing/checkout"); fakeEnv.STRIPE_PRICE_PRO = "price_pro"; const customer = (status: string | null, price: string | null) => accountSql("u1") .exec(`INSERT OR REPLACE INTO billing_customers (account_id, stripe_customer_id, subscription_status, price_id, cancel_at_period_end, subscription_event_at, updated_at) VALUES ('u1', 'cus_1', ${status ? `'${status}'` : "NULL"}, ${price ? `'${price}'` : "NULL"}, 0, 0, 0)`); try { await setPlan("u1", "pro", "admin"); await followBillingPlan("u1"); expect((await billingSettings("u1")).plan.id).toBe("free"); customer("active", "price_pro"); await setPlan("u1", "free", "admin"); await followBillingPlan("u1"); expect((await billingSettings("u1")).plan.id).toBe("pro"); customer("active", "price_other"); await setPlan("u1", "free", "admin"); await followBillingPlan("u1"); expect((await billingSettings("u1")).plan.id).toBe("free"); await setPlan("u1", "free", "billing"); expect((await billingSettings("u1")).plan.id).toBe("free"); customer("canceled", "price_pro"); await setPlan("u1", "pro", "admin"); await followBillingPlan("u1"); expect((await billingSettings("u1")).plan.id).toBe("free"); } finally { delete fakeEnv.STRIPE_PRICE_PRO; } }); test("commits are dated inside the reservation period", async () => { const hold = await reserveUsage({ id: "late", accountId: "u1", meter: "compute.editor", quantity: 10 }); await commitUsage({ ...hold, period: "2020-01" }, { quantity: 3 }); expect(quantity("u1", "compute.editor", "2020-01")).toBe(3); const day = accountSql("u1") .query("SELECT day FROM usage_days WHERE account_id = 'u1' AND meter = 'compute.editor'") .get(); expect(day).toEqual({ day: "2020-01-31" }); }); test("counting bodies meter cancelled streams once", async () => { const seen: number[] = []; const source = new ReadableStream({ pull(controller) { controller.enqueue(new Uint8Array(4)); }, }); const body = countingBody(source, (bytes) => seen.push(bytes)); if (!body) throw new Error("expected a body"); const reader = body.getReader(); await reader.read(); await reader.read(); await reader.cancel(); expect(seen).toEqual([8]); }); });