import { beforeEach, describe, expect, mock, test } from "bun:test"; import { fakeD1 } from "../metering/fake-d1.test-helper"; import { scopedTestState } from "./scoped.test-helper"; let d1 = fakeD1(); const released: string[] = []; mock.module("cloudflare:workers", () => ({ env: { get DB() { return d1.binding; }, }, waitUntil: () => undefined, })); const scoped = scopedTestState(); scoped.install(); type Row = [string, string, string, string, number, number, number | null]; function addSites(...rows: Row[]): void { for (const [id, owner, domain, status, claimed, updated, verified] of rows) { scoped.site({ id, owner_id: owner, custom_domain: domain, domain_status: status, domain_claimed_at: claimed, updated_at: updated, domain_verified_at: verified, }); } } mock.module("./site", () => ({ releaseSiteDomain: async (site: { id: string }) => void released.push(site.id) })); const { sweepCustomDomains } = await import("./domain-sweep"); const { DOMAIN_GRACE_MS, saveDomainAddon } = await import("../billing/domain-addon"); const HOUR = 60 * 60 * 1000; const NOW = 1_800_000_000_000; beforeEach(() => { d1 = fakeD1(); scoped.reset(); released.length = 0; d1.db.run(` INSERT INTO accounts (id, name, kind) VALUES ('u1', 'alice', 'user'), ('u2', 'bob', 'user'); INSERT INTO repos VALUES ('r1', 'u1', 'blog'), ('r2', 'u2', 'docs'); `); }); describe("custom domain sweep", () => { test("never expires a verified domain, even when its certificate status is momentarily not active", async () => { const at = NOW - 200 * HOUR; addSites( ["live", "u2", "a.test", "active", at, 0, at], ["blip", "u2", "b.test", "pending (certificate pending_validation)", at, 0, at], ); await sweepCustomDomains(NOW); expect(released).toEqual([]); }); test("expires only never-verified claims older than 72 hours", async () => { addSites( ["old", "u2", "a.test", "pending (certificate pending)", NOW - 80 * HOUR, 0, null], ["fresh", "u2", "b.test", "pending", NOW - HOUR, 0, null], ["renewing", "u2", "c.test", "active (certificate pending)", NOW - 80 * HOUR, 0, null], ); await sweepCustomDomains(NOW); expect(released.sort()).toEqual(["old"]); }); test("releases every domain of an account once its lapsed add-on's grace ends", async () => { addSites(["s1", "u1", "a.test", "active", NOW, 0, NOW], ["s2", "u1", "b.test", "active", NOW, 0, null]); await saveDomainAddon("u1", { subscriptionId: "sub", itemId: "si", status: "canceled", quantity: 2 }, 1); await sweepCustomDomains(Date.now()); expect(released).toEqual([]); await sweepCustomDomains(Date.now() + DOMAIN_GRACE_MS + 1); expect(released.sort()).toEqual(["s1", "s2"]); const row = scoped.account("u1").query("SELECT lapsed_at FROM billing_addons WHERE account_id = 'u1'").get(); expect(row).toEqual({ lapsed_at: null }); }); });