import { beforeEach, describe, expect, mock, test } from "bun:test"; import { Database } from "bun:sqlite"; import { readFileSync } from "node:fs"; import { fakeD1 } from "./fake-d1.test-helper"; let d1 = fakeD1(); mock.module("cloudflare:workers", () => ({ env: { get DB() { return d1.binding; }, }, waitUntil: () => undefined, })); const { ACCOUNT_SCHEMA } = await import("../scoped-db/schema.gen"); const { leaderboardRows, publishUsageLeaderboard } = await import("./leaderboard"); const NOW = Date.parse("2026-10-01T00:03:00Z"); function account(id: string, usage: Array<[string, string, number]>) { const db = new Database(":memory:"); for (const statement of ACCOUNT_SCHEMA) db.run(statement); for (const [meter, period, quantity] of usage) { db.query( "INSERT INTO usage_periods (account_id, meter, period, quantity, reserved, updated_at) VALUES (?, ?, ?, ?, 0, 0)", ).run(id, meter, period, quantity); } return { db, sql: { exec: (query: string, ...params: Array) => { const rows = db.query(query).all(...params) as never[]; return { toArray: () => rows }; }, }, }; } beforeEach(() => { d1 = fakeD1(); d1.db.exec(readFileSync(new URL("../../../migrations/0063_usage_leaderboard.sql", import.meta.url), "utf8")); }); describe("usage leaderboard", () => { test("accounts publish this and last period, and the ranking keeps the heaviest per meter", async () => { const a = account("a", [ ["compute.ci", "2026-10", 5], ["compute.ci", "2026-09", 50], ]); const b = account("b", [["compute.ci", "2026-10", 9]]); const c = account("c", [["compute.ci", "2026-10", 1]]); for (const [id, store] of [ ["a", a], ["b", b], ["c", c], ] as const) await publishUsageLeaderboard(id, store.sql, NOW); expect(await leaderboardRows("2026-10", 2)).toEqual([ { account_id: "b", meter: "compute.ci", quantity: 9 }, { account_id: "a", meter: "compute.ci", quantity: 5 }, ]); expect(await leaderboardRows("2026-09", 2)).toEqual([{ account_id: "a", meter: "compute.ci", quantity: 50 }]); b.db.run("DELETE FROM usage_periods"); await publishUsageLeaderboard("b", b.sql, NOW); expect((await leaderboardRows("2026-10", 5)).map((row) => row.account_id)).toEqual(["a", "c"]); }); });