147 lines · 9.6 KB · TypeScriptRaw
/** * SHARED 4 (src/space/space.ts): the roster chain the space keeps for the phones, record versions and signed * deletions, and what two acts at once must never do. Every pair of the acts that move a departed member's bytes * (Keep by one member, Keep by another, the owner deleting, the thirty-day sweep) is run at once on a fresh space, * and after each the bytes counted to everyone equal the bytes the space holds. A put racing an epoch move never * lands under the old key; a leave during a move leaves the epoch due; two adds of one person add them once. */import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Business } from "../src/business.ts";import { LEAVE_MS } from "../src/space/space.ts";import { fakes } from "./calling.ts";import { accept, found, hashOf, inSpace, person, record, signed, upload, wrap, type Person } from "./shared_space_people.ts";vi.setConfig({ testTimeout: 600_000 });beforeEach(() => { fakes();});afterEach(() => { vi.restoreAllMocks();});async function circle(count: number): Promise<Person[]> { const people: Person[] = []; for (let i = 0; i < count; i++) people.push(await person()); for (let i = 0; i < count; i++) for (let j = i + 1; j < count; j++) await accept(people[i]!, people[j]!); return people;}async function sharedOf(p: Person, space: string): Promise<number> { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(p.slug)), (_i: Business, state) => state.storage.sql.exec<{ n: number | null }>("SELECT SUM(bytes) AS n FROM space_bytes WHERE space = ?", space).one().n ?? 0);}async function held(space: string): Promise<number> { return inSpace(space, (sql) => { const files = sql.exec<{ n: number | null }>("SELECT SUM(size) AS n FROM file").one().n ?? 0; const records = sql.exec<{ n: number | null }>("SELECT SUM(bytes) AS n FROM record WHERE deleted = 0").one().n ?? 0; return files + records; });}describe("the roster chain", () => { it("is kept in order with the act it rides on, refused (and the act with it) when it does not follow the last", async () => { const [a, b, c] = await circle(3); const { space, id } = await found(a!, [b!, c!]); const first = await signed(a!, id[a!.number]!, space, 0, "", { kind: "epoch", epoch: 2 }); const wraps = { [id[a!.number]!]: wrap(), [id[b!.number]!]: wrap(), [id[c!.number]!]: wrap() }; expect((await a!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, wraps, statement: first })).status).toBe(200); // Not following the last: refused, and the epoch does not move. const stray = await signed(a!, id[a!.number]!, space, 1, "0".repeat(64), { kind: "epoch", epoch: 3 }); const refused = await a!.ask<{ code: string }>("POST", `/v1/spaces/${space}/epoch`, { epoch: 3, wraps, statement: stray }); expect(refused.body.code).toBe("roster_moved"); expect((await a!.ask<{ epoch: number; roster: { seq: number; hash: string } }>("GET", `/v1/spaces/${space}`)).body).toMatchObject({ epoch: 2, roster: { seq: 0, hash: await hashOf(first) } }); // A member's own statement (leaving) follows on. const leaving = await signed(c!, id[c!.number]!, space, 1, await hashOf(first), { kind: "leave" }); expect((await c!.ask("POST", `/v1/spaces/${space}/leave`, { statement: leaving })).status).toBe(200); const listed = await b!.ask<{ statements: { seq: number; text: string }[] }>("GET", `/v1/spaces/${space}/roster?after=-1`); expect(listed.body.statements.map((s) => s.text)).toEqual([first, leaving]); expect((await b!.ask<{ statements: unknown[] }>("GET", `/v1/spaces/${space}/roster?after=0`)).body.statements).toHaveLength(1); expect((await b!.ask<{ code: string }>("POST", `/v1/spaces/${space}/roster`, { statement: "t1:not-a-statement" })).body.code).toBe("bad_statement"); });});describe("record versions and signed deletions", () => { it("a record moves up one version at a time, and a deletion carries its signature for the other phones", async () => { const [a, b] = await circle(2); const { space } = await found(a!, [b!]); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [{ ...record("r", "item", "x", [], 1), version: 1 }] })).status).toBe(200); expect((await b!.ask<{ code: string }>("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [{ ...record("r", "item", "x", [], 1), version: 1 }] })).body.code).toBe("bad_version"); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [{ ...record("r", "item", "x", [], 1), version: 2 }] })).status).toBe(200); expect((await a!.ask<{ code: string }>("POST", `/v1/spaces/${space}/records/delete`, { ids: ["r"], tombs: { r: { version: 2, sig: `s1:${"A".repeat(86)}` } } })).body.code).toBe("bad_tomb"); const sig = `s1:${"B".repeat(86)}`; expect((await a!.ask("POST", `/v1/spaces/${space}/records/delete`, { ids: ["r"], tombs: { r: { version: 3, sig } } })).status).toBe(200); const list = await b!.ask<{ deleted: string[]; tombs: Record<string, unknown> }>("GET", `/v1/spaces/${space}/records`); expect(list.body.deleted).toEqual(["r"]); expect(list.body.tombs.r).toMatchObject({ version: 3, sig }); });});describe("two acts at once", () => { type Act = "keep_a" | "keep_b" | "delete" | "sweep"; const ACTS: Act[] = ["keep_a", "keep_b", "delete", "sweep"]; const PAIRS: [Act, Act][] = ACTS.flatMap((x, i) => ACTS.slice(i).map((y): [Act, Act] => [x, y])); for (const [one, two] of PAIRS) { it(`${one} with ${two}: the bytes counted to everyone equal the bytes the space holds`, async () => { const [a, b, c] = await circle(3); const { space, id } = await found(a!, [b!, c!]); const f1 = await upload(c!, space, 700); const f2 = await upload(c!, space, 300); expect((await c!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [record("c1", "item", "x", [f1.file], 1), record("c2", "item", "x", [f2.file], 1)] })).status).toBe(200); expect((await c!.ask("POST", `/v1/spaces/${space}/leave`, {})).status).toBe(200); if (one === "sweep" || two === "sweep") await inSpace(space, (sql) => sql.exec("UPDATE member SET left_at = ? WHERE id = ?", Date.now() - LEAVE_MS - 1000, id[c!.number])); const act = (x: Act): Promise<unknown> => { if (x === "keep_a") return a!.ask("POST", `/v1/spaces/${space}/keep`, { member: id[c!.number] }); if (x === "keep_b") return b!.ask("POST", `/v1/spaces/${space}/keep`, { member: id[c!.number] }); if (x === "delete") return a!.ask("POST", `/v1/spaces/${space}/records/delete`, { ids: ["c1", "c2"] }); return runDurableObjectAlarm(env.SPACES.get(env.SPACES.idFromName(space))); }; await Promise.all([act(one), act(two)]); const counted = (await sharedOf(a!, space)) + (await sharedOf(b!, space)) + (await sharedOf(c!, space)); const queued = await inSpace(space, (sql) => (sql.exec("SELECT name FROM sqlite_master WHERE name = 'outbox'").toArray().length ? sql.exec<{ n: number | null }>("SELECT SUM(-delta) AS n FROM outbox WHERE kind = 'refund'").one().n ?? 0 : 0)); expect({ counted: counted - queued, held: await held(space) }).toEqual({ counted: await held(space), held: await held(space) }); }); } it("a put racing an epoch move never lands under the old key", async () => { const [a, b] = await circle(2); const { space, id } = await found(a!, [b!]); const [put, moved] = await Promise.all([ b!.ask<{ code?: string }>("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [record("p", "item", "x", [], 1)] }), a!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, wraps: { [id[a!.number]!]: wrap(), [id[b!.number]!]: wrap() } }), ]); expect(moved.status).toBe(200); if (put.status === 200) { // Landed before the move: then it is a stale record to re-wrap, written while epoch 1 was current. const row = await inSpace(space, (sql) => sql.exec<{ epoch: number }>("SELECT epoch FROM record WHERE id = 'p'").one()); expect(row.epoch).toBe(1); } else { expect(put.body.code).toMatch(/^(key_moved|stale_epoch)$/); expect(await inSpace(space, (sql) => sql.exec("SELECT 1 FROM record WHERE id = 'p'").toArray().length)).toBe(0); } }); it("a leave during an epoch move leaves the epoch due", async () => { const [a, b, c, d] = await circle(4); const { space, id } = await found(a!, [b!, c!, d!]); const [moved, left] = await Promise.all([ a!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, remove: [id[d!.number]], wraps: { [id[a!.number]!]: wrap(), [id[b!.number]!]: wrap(), [id[c!.number]!]: wrap() } }), b!.ask("POST", `/v1/spaces/${space}/leave`, {}), ]); expect(left.status).toBe(200); const due = (await a!.ask<{ rekey_due: boolean }>("GET", `/v1/spaces/${space}`)).body.rekey_due; // b left before the move (it then refused, b had no place in it), during it, or after it: due in every case. if (moved.status === 200) expect(due).toBe(true); }); it("two adds of one person at once add them once", async () => { const [a, b, c] = await circle(3); const { space } = await found(a!, [b!]); const [x, y] = await Promise.all([a!.ask("POST", `/v1/spaces/${space}/members`, { numbers: [c!.number] }), a!.ask("POST", `/v1/spaces/${space}/members`, { numbers: [c!.number] })]); expect([x.status, y.status].filter((s) => s === 200)).toHaveLength(1); expect(await inSpace(space, (sql) => sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM member WHERE number = ? AND left_at IS NULL", c!.number).one().n)).toBe(1); });});