| 1 | import { describe, expect, it } from "vitest"; |
| 2 | import { rollupDaily } from "../src/rollup"; |
| 3 | import { answer, FakeD1, fakeRunner } from "./support"; |
| 4 | |
| 5 | describe("rollupDaily", () => { |
| 6 | it("backfills the retention window on an empty store and stores totals only", async () => { |
| 7 | const { runner, seen } = fakeRunner(answer); |
| 8 | const db = new FakeD1(); |
| 9 | const result = await rollupDaily(runner, db, new Date("2026-11-12T02:17:00Z")); |
| 10 | expect(result).toMatchObject({ from: "2026-08-14", to: "2026-11-12" }); |
| 11 | expect(db.rows.size).toBeGreaterThan(8); |
| 12 | expect(JSON.stringify([...db.rows.values()])).not.toMatch(/install_id|index1|[0-9a-f]{8}-[0-9a-f]{4}-/); |
| 13 | expect(seen.some((sql) => sql.includes("2026-08-14T00:00:00Z"))).toBe(true); |
| 14 | expect(db.rows.get("2026-11-10|active_installs|all|all")?.value).toBe(4); |
| 15 | }); |
| 16 | |
| 17 | it("is idempotent and only re-reads the last two days once data exists", async () => { |
| 18 | const db = new FakeD1(); |
| 19 | await rollupDaily(fakeRunner(answer).runner, db, new Date("2026-11-12T02:17:00Z")); |
| 20 | const size = db.rows.size; |
| 21 | const second = fakeRunner(answer); |
| 22 | const result = await rollupDaily(second.runner, db, new Date("2026-11-12T02:17:00Z")); |
| 23 | expect(db.rows.size).toBe(size); |
| 24 | expect(result.from).toBe("2026-11-10"); |
| 25 | expect(second.seen.every((sql) => sql.includes("2026-11-10T00:00:00Z"))).toBe(true); |
| 26 | }); |
| 27 | |
| 28 | it("stores only the all and funnel dimensions, never a per-version or per-model row", async () => { |
| 29 | const db = new FakeD1(); |
| 30 | await rollupDaily(fakeRunner((sql) => (sql.includes("blob6 AS key") ? [{ day: "2026-11-10", key: "0.10.3-acme.internal.alice", installs: "1", sessions: "7" }] : answer(sql))).runner, db, new Date("2026-11-12T02:17:00Z")); |
| 31 | const dims = new Set([...db.rows.values()].map((r) => r.dim)); |
| 32 | expect([...dims].sort()).toEqual(["all", "funnel"]); |
| 33 | expect(JSON.stringify([...db.rows.values()])).not.toContain("acme"); |
| 34 | }); |
| 35 | |
| 36 | it("backfills in chunks and writes each one, so a failing later chunk keeps the earlier days", async () => { |
| 37 | const db = new FakeD1(); |
| 38 | let calls = 0; |
| 39 | const runner = fakeRunner((sql) => { |
| 40 | if (++calls > 10 * 2) throw new Error("boom"); |
| 41 | return answer(sql); |
| 42 | }).runner; |
| 43 | await expect(rollupDaily(runner, db, new Date("2026-11-12T02:17:00Z"))).rejects.toThrow("boom"); |
| 44 | expect(db.rows.size).toBeGreaterThan(0); |
| 45 | }); |
| 46 | |
| 47 | it("writes nothing when the source returns no rows", async () => { |
| 48 | const db = new FakeD1(); |
| 49 | const result = await rollupDaily(fakeRunner(() => []).runner, db, new Date("2026-11-12T02:17:00Z")); |
| 50 | expect(result.rows).toBe(0); |
| 51 | expect(db.rows.size).toBe(0); |
| 52 | }); |
| 53 | }); |
| 54 |