import { beforeEach, describe, expect, mock, test } from "bun:test";
import { readFileSync } from "node:fs";
import { fakeD1 } from "../metering/fake-d1.test-helper";
let d1 = fakeD1();
const stopped: string[] = [];
const fakeEnv: Record<string, unknown> = {
get DB() {
return d1.binding;
},
KV: { get: async () => null, put: async () => undefined, delete: async () => undefined },
EDITOR_CONTAINER: { getByName: (name: string) => ({ stop: async () => stopped.push(name) && 0 }) },
METERING_PLANS: "",
PUBLIC_URL: "https://forge.test",
};
mock.module("cloudflare:workers", () => ({
env: fakeEnv,
waitUntil: () => undefined,
}));
const { closeContainerSession, closeExpiredContainerSessions, closeOrphanSession, openContainerSession } =
await import("./container-meter");
const { setPlan } = await import("../metering/quota");
const editorTable = readFileSync(new URL("../../../migrations/0010_editor.sql", import.meta.url), "utf8");
function billed(): number {
const row = d1.db.query("SELECT SUM(quantity) AS q FROM usage_events WHERE meter = 'compute.editor'").get() as {
q: number | null;
} | null;
return row?.q ?? 0;
}
function backdate(id: string, ms: number) {
d1.db.query("UPDATE editor_container_sessions SET started_at = started_at - ? WHERE id = ?").run(ms, id);
}
beforeEach(async () => {
d1 = fakeD1();
d1.db.exec(editorTable.slice(0, editorTable.indexOf("CREATE INDEX")));