Cotton code
121 lines · 7.5 KB · TypeScriptRaw
/** * SNAPSHOTS 1 (coordinator for the owner, 27 Nov 2026; assets/design/shared/RESTORE.md Part 2): a copy of the rows as * stored, outside the object, sealed under the account's own key kept in the directory. Off by default; a weekly full * and daily changes; restored on a frozen account, row for row, with a new generation (RESTORE 2). */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { directory } from "../src/directory.ts";import { snapshotsOn } from "../src/snapshots.ts";import { ADMIN, http, personalObject, TODOS_OPEN } from "./personal.ts";const phone = (credential: string) => ({ authorization: `Bearer ${credential}` });const object = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));type Run = { done?: boolean; idle?: boolean; manifest?: { kind: string; stamp: string; base: number; upto: number; rows: number; parts: { key: string }[] } };/** Every row of the object as stored (live and tombstones), in key order: what a restore must give back. */async function stored(slug: string): Promise<string[]> {  return runInDurableObject(object(slug), (_i, state) =>    state.storage.sql      .exec<Record<string, SqlStorageValue>>("SELECT table_id, id, data, owner, version, deleted, created_at, updated_at FROM rows ORDER BY table_id, id")      .toArray()      .map((r) => JSON.stringify(r)),  );}async function runUntilDone(slug: string, kind?: "full" | "daily"): Promise<NonNullable<Run["manifest"]>> {  for (let n = 0; n < 20; n++) {    const got = await http<Run>(slug, "POST", "/v1/admin/snapshots/run", { ...(n === 0 && kind ? { kind } : {}) }, ADMIN);    expect(got.status, JSON.stringify(got.body)).toBe(200);    if (got.body.done && got.body.manifest) return got.body.manifest;  }  throw new Error("the copy never finished");}describe("snapshots", () => {  it("follow the account's own switch first, then the Worker's SNAPSHOTS_ALL, which is off unless it says on", () => {    for (const all of [undefined, "", "off", "ON", "true"]) expect(snapshotsOn(null, { SNAPSHOTS_ALL: all })).toBe(false);    expect(snapshotsOn(null, { SNAPSHOTS_ALL: "on" })).toBe(true);    expect(snapshotsOn("off", { SNAPSHOTS_ALL: "on" })).toBe(false);    expect(snapshotsOn("on", {})).toBe(true);  });  it("are off by default, and only the admin token switches them", async () => {    const slug = "snapshots-off";    const { owner } = await personalObject(slug, { open: TODOS_OPEN });    expect((await http<{ on: boolean }>(slug, "GET", "/v1/admin/snapshots", undefined, ADMIN)).body.on).toBe(false);    expect((await http(slug, "POST", "/v1/admin/snapshots", { on: true }, { authorization: `Bearer ${owner}` })).status).toBe(403);    expect((await http<{ on: boolean }>(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN)).body.on).toBe(true);    expect((await http<{ on: boolean }>(slug, "POST", "/v1/admin/snapshots", { on: false }, ADMIN)).body.on).toBe(false);  });  it("write a weekly full and daily changes, sealed under a key kept in the directory, then restore row for row", async () => {    const slug = "snapshots-cycle";    const { credential } = await personalObject(slug, { open: TODOS_OPEN });    const ids: string[] = [];    for (let i = 0; i < 12; i++) {      const made = await http<{ changed: { id: string }[] }>(slug, "POST", "/v1/act", { act: "create", args: { table: "todo", data: { title: `Invented ${i}` } } }, phone(credential));      ids.push(made.body.changed[0]!.id);    }    await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN);    const full = await runUntilDone(slug, "full");    expect(full.kind).toBe("full");    expect(full.rows).toBeGreaterThanOrEqual(12);    // Sealed: the part is neither JSON nor gzip, and holds no title.    const part = new Uint8Array(await (await env.MEDIA.get(`_snapshots/weekly/${slug}/${full.stamp}/${full.parts[0]!.key}`))!.arrayBuffer());    expect(part[0] === 0x1f && part[1] === 0x8b).toBe(false);    expect(new TextDecoder().decode(part)).not.toContain("Invented");    expect(await directory(env).snapshotKeyKept(slug)).toBe(true);    expect(await env.MEDIA.get(`${slug}/.snapshot-key`)).toBeNull();    // Changes after it: two made, one edited, one deleted (a tombstone).    for (let i = 0; i < 2; i++) await http(slug, "POST", "/v1/act", { act: "create", args: { table: "todo", data: { title: `Later ${i}` } } }, phone(credential));    await http(slug, "POST", "/v1/act", { act: "update", args: { table: "todo", id: ids[0], data: { title: "Edited" } } }, phone(credential));    await http(slug, "POST", "/v1/act", { act: "delete", args: { table: "todo", id: ids[1] } }, phone(credential));    const daily = await runUntilDone(slug, "daily");    expect(daily.base).toBe(full.upto);    expect(daily.rows, "the four changes (and any row the phone's own calls moved)").toBeGreaterThanOrEqual(4);    const kept = await stored(slug);    const generationBefore = (await http<{ generation: string }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.generation;    const versionBefore = (await http<{ version: number }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.version;    // The damage: every to-do deleted.    for (const id of ids) await http(slug, "POST", "/v1/act", { act: "delete", args: { table: "todo", id } }, phone(credential));    expect(await stored(slug)).not.toEqual(kept);    // Restored: only frozen, from the full and the daily after it, row for row.    expect((await http<{ code: string }>(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN)).body.code).toBe("not_frozen");    await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN);    const begun = await http<{ snapshots: number }>(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN);    // The full and every daily after it: the alarm may write a daily of its own, at once after the full (L2).    expect(begun.body.snapshots).toBeGreaterThanOrEqual(2);    let step: { done: boolean; version?: number; generation?: string } = { done: false };    for (let n = 0; n < 20 && !step.done; n++) step = (await http<typeof step>(slug, "POST", "/v1/admin/snapshots/restore/step", {}, ADMIN)).body;    expect(step.done).toBe(true);    expect(await stored(slug), "every row as it was stored at the daily").toEqual(kept);    expect(step.version).toBeGreaterThan(versionBefore + 999);    expect(step.generation).not.toBe(generationBefore);    await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN);    const sync = await http<{ generation: string; restored_to: string }>(slug, "GET", "/v1/sync?since=0&limit=1", undefined, phone(credential));    expect(sync.body.generation).toBe(step.generation);    expect(sync.body.restored_to).toBeTruthy();  });  it("keep the 4 newest weeklies and the 7 newest dailies", async () => {    const slug = "snapshots-keep";    await personalObject(slug, { open: TODOS_OPEN });    await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN);    for (let i = 0; i < 6; i++) {      await runUntilDone(slug, "full");      await new Promise((done) => setTimeout(done, 5));    }    for (let i = 0; i < 9; i++) {      await runUntilDone(slug, "daily");      await new Promise((done) => setTimeout(done, 5));    }    const listed = await http<{ weekly: string[]; daily: string[] }>(slug, "GET", "/v1/admin/snapshots", undefined, ADMIN);    expect(listed.body.weekly.length).toBe(4);    expect(listed.body.daily.length).toBe(7);  });});