/** * THE CHANGE LOG TRIMMED TO ITS BUDGET AT HIS SIZE (coordinator for the owner, 22 Nov 2026). His live log: 99,930 * entries, 2.86 GB, about 28 KB an entry. An invented log built the same (old-style entries holding a sealed body * before and after, written over the last 90 days), then the account's switch set (30 days, 500 MB), and the alarm * run until it is done: each alarm's time (a request waits behind it, so the longest is the worst wait), a read * between alarms, and the file before and after. Small by default; `BIG_OBJECT=1` builds it at his size (2.8 GB of * local disk while it runs). Invented records only. */import { env, runInDurableObject } from"cloudflare:test";import { describe, expect, it } from"vitest";import { BIG } from"./big_object.ts";import { ADMIN, answer, http, NOTES_OPEN, personalObject } from"./personal.ts";const SCALE = BIG ? 1 : 1 / 100;const ENTRIES = Math.round(99_930 * SCALE);const BUDGET = Math.round(500_000_000 * SCALE);const HALF = 14_000; // characters of a sealed body, before and after each: 28 KB an entryconst out: string[] = [];describe("the change log's budget at his size", () => { it("trims to 30 days and the budget in steps the object stays answerable between", async () => {const slug = "change-budget-big";const { owner } = await personalObject(slug, { open: NOTES_OPEN.open });const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));const now = Date.now();for (let done = 0; done < ENTRIES; done += 1_000) {const k = Math.min(1_000, ENTRIES - done);await runInDurableObject(stub, (_i, s) => s.storage.sql.exec(`WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM c WHERE i < ${k}) INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) SELECT strftime('%Y-%m-%dT%H:%M:%fZ', ? / 1000.0 - (90.0 * 86400) * (1.0 - (? + i) * 1.0 / ?), 'unixepoch'), NULL, 'update', 'note', lower(hex(randomblob(16))), 'update', json_object('_sealed', 'v1.' || substr(hex(randomblob(${HALF / 2})), 1, ${HALF})), json_object('_sealed', 'v1.' || substr(hex(randomblob(${HALF / 2})), 1, ${HALF})), 1 FROM c`, now, done, ENTRIES, ), ); }const file = () => runInDurableObject(stub, (_i, s) => s.storage.sql.databaseSize);const count = () => runInDurableObject(stub, (_i, s) => Number(s.storage.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM change").one().n));const before = await file();const built = await count(); out.push(`built: ${built} entries, file ${(before / 1e6).toFixed(0)} MB`);// Off by default: an alarm trims nothing (all entries are inside 90 days and under 100,000).await runInDurableObject(stub, async (instance) => (instance as unknown as { alarm(): Promise<void> }).alarm()); expect(await count(), "nothing goes before the switch").toBe(built); expect((await http(slug, "PUT", "/v1/admin/business", { change_days: 30, change_bytes: BUDGET }, ADMIN)).status).toBe(200);let alarms = 0;let longest = 0;let slowestRead = 0;const t0 = Date.now();for (;;) {// The object's own alarm, called directly and timed (a request waits behind it); the next it would set is taken// off, so no alarm runs between these on its own.const took = await runInDurableObject(stub, async (instance, s) => {await s.storage.deleteAlarm();const a = Date.now();await (instance as unknown as { alarm(): Promise<void> }).alarm();const ms = Date.now() - a;await s.storage.deleteAlarm();return ms; }); longest = Math.max(longest, took); alarms++;const r = Date.now();await answer(slug, owner, "list_records", { table: "note", limit: 1 }); slowestRead = Math.max(slowestRead, Date.now() - r);const left = await runInDurableObject(stub, (_i, s) => {const size = s.storage.sql.exec<{ bytes: number; below: number }>("SELECT bytes, below FROM change_size").toArray()[0];const oldest = s.storage.sql.exec<{ at: string }>("SELECT MIN(at) AS at FROM change").one().at;const counted = size ? !s.storage.sql.exec("SELECT 1 FROM change WHERE id <= ? LIMIT 1", size.below).toArray().length : false;return { size, oldest, counted }; });const done = left.counted && left.size!.bytes <= BUDGET && left.oldest >= newDate(Date.now() - 30 * 86_400_000).toISOString();if (done || alarms > 500) break; }const after = await file();const kept = await count(); out.push(`switch on: ${alarms} alarms in ${((Date.now() - t0) / 1000).toFixed(0)} s, the longest ${longest} ms, the slowest read between them ${slowestRead} ms`); out.push(`after: ${kept} entries, file ${(after / 1e6).toFixed(0)} MB (was ${(before / 1e6).toFixed(0)} MB)`);const summary = await answer<{ change_log: { chars?: { counted: number; ready: boolean } } }>(slug, owner, "storage_summary", { parts: false }); out.push(`storage_summary change_log.chars: ${JSON.stringify(summary.change_log.chars)}`);// The run's figures, said where a passing test can say them: as the reason a big run stops (STORAGE.md quotes them).if (BIG) thrownewError(`RESULT\n${out.join("\n")}`); expect(summary.change_log.chars?.ready).toBe(true); expect(summary.change_log.chars!.counted).toBeLessThanOrEqual(BUDGET); expect(kept).toBeLessThan(built); expect(after).toBeLessThan(before); });});