Cotton code
171 lines · 9.9 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { afterAll, describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { resolverForTests, type Resolve } from "../src/mail/dns.ts";import { BIG } from "./big_object.ts";import { http, personalObject } from "./personal.ts";/** * MAIL ON THE PERSON'S OWN DOMAIN, AT SIZE (OWN-MAIL.md "What * proves each stage"): an invented person whose object already holds 100,000 * mails in 60,000 conversations (every row sealed, a 3,000-byte body as the * object holds it), and 500 messages arriving over one hour, a fifth of them * replies into a conversation already held, each with a small attachment. * * Measured, per arrival: the object's own milliseconds and the rows its * statements read. The rule: an arrival reads what it touches (its email, its * thread, its people, its tally), never a scan of the 100,000: the rows * it reads of the rows table stay a handful whatever is held. Printed * (`--disableConsoleIntercept`); `BIG_OBJECT=1` runs it at full size, else at * a fortieth. */const SCALE = BIG ? 1 : 1 / 40;const HELD = Math.round(100_000 * SCALE);const HELD_THREADS = Math.round(60_000 * SCALE);const ARRIVING = BIG ? 500 : 60;const HOUR = 3_600_000;const SLUG = "ownmail-big";const DOMAIN = "bigmail.example";afterAll(() => resolverForTests(null));function dns(code: string): Resolve {  const table: Record<string, string[]> = {    [`MX ${DOMAIN}`]: ["13 route1.mx.cloudflare.net"],    [`TXT ${DOMAIN}`]: ["v=spf1 include:_spf.mx.cloudflare.net ~all"],    [`TXT cf2024-1._domainkey.${DOMAIN}`]: ["v=DKIM1; p=MIIB"],    [`TXT cf-bounce._domainkey.${DOMAIN}`]: ["v=DKIM1; p=MIIC"],    [`TXT _dmarc.${DOMAIN}`]: ["v=DMARC1; p=none"],    [`TXT _cotton.${DOMAIN}`]: [`cotton-verify=${code}`],  };  return async (name, type) => table[`${type} ${name}`] ?? [];}const message = (i: number, root: number | null) =>  new TextEncoder().encode(    [      "Authentication-Results: mx.cloudflare.net; dkim=pass header.d=example.org; spf=pass smtp.mailfrom=example.org; dmarc=pass header.from=example.org",      `From: Sender ${i % 37} <sender${i % 37}@example.org>`,      `To: me@${DOMAIN}`,      `Subject: ${root === null ? `Invented subject ${i}` : `Re: Invented subject ${root}`}`,      `Date: ${new Date(Date.UTC(2026, 10, 22, 9, 0, 0) + i * 7_000).toUTCString().replace("GMT", "+0000")}`,      `Message-ID: <big.${i}@example.org>`,      ...(root === null ? [] : [`In-Reply-To: <big.${root}@example.org>`, `References: <big.${root}@example.org>`]),      "MIME-Version: 1.0",      'Content-Type: multipart/mixed; boundary="b"',      "",      "--b",      "Content-Type: text/plain; charset=utf-8",      "",      `Invented words for message ${i}. `.repeat(60),      "--b",      'Content-Type: application/pdf; name="note.pdf"',      'Content-Disposition: attachment; filename="note.pdf"',      "Content-Transfer-Encoding: base64",      "",      btoa(`invented attachment ${i} `.repeat(40)),      "--b--",      "",    ].join("\r\n"),  );describe("mail on the person's own domain, on a very large object", () => {  it("keeps each of an hour's arrivals in the rows it touches, however much mail is held", async () => {    const { credential } = await personalObject(SLUG, { arrival: true });    const auth = { authorization: `Bearer ${credential}` };    const added = await http<{ proof: { value: string } }>(SLUG, "POST", "/v1/mail/domains", { domain: DOMAIN }, auth);    resolverForTests(dns(added.body.proof.value.slice("cotton-verify=".length)));    expect((await http<{ proved: boolean }>(SLUG, "POST", "/v1/mail/domains/check", { domain: DOMAIN }, auth)).body.proved).toBe(true);    await http(SLUG, "POST", "/v1/mail/addresses", { address: `me@${DOMAIN}`, isDefault: true }, auth);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));    const made = Date.now();    await runInDurableObject(stub, (_i, state) => {      const sql = state.storage.sql;      const top = Number(sql.exec<{ v: number }>("SELECT COALESCE(MAX(version), 0) AS v FROM rows").one().v);      sql.exec(        `WITH RECURSIVE c(t) AS (SELECT 1 UNION ALL SELECT t + 1 FROM c WHERE t < ?)         INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at)         SELECT 'email_thread', printf('held-thread-%06d', t), json_object('first_at', '2020-01-01T00:00:00.000Z', 'last_at', strftime('%Y-%m-%dT%H:%M:%fZ', '2020-01-01', '+' || t || ' minutes'), 'sealed_enc', 's1:' || hex(randomblob(150)), 'dek_enc', 'a1:x', 'seal_v', 1), NULL, ? + t, 0, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z' FROM c`,        HELD_THREADS,        top,      );      sql.exec(        `WITH RECURSIVE c(t) AS (SELECT 1 UNION ALL SELECT t + 1 FROM c WHERE t < ?)         INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at)         SELECT 'email', printf('held-email-%06d', t), json_object('thread_id', printf('held-thread-%06d', 1 + t % ?), 'sent_at', strftime('%Y-%m-%dT%H:%M:%fZ', '2020-01-01', '+' || (t * 30) || ' minutes'), 'sealed_enc', 's1:' || hex(randomblob(1500)), 'dek_enc', 'a1:x', 'seal_v', 1), NULL, ? + t, 0, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z' FROM c`,        HELD,        HELD_THREADS,        top + HELD_THREADS,      );    });    // A live object keeps its day counts as it writes; the fill above went round them, so the recount the alarm    // would carry is finished here first, and what follows measures an arrival, not the catch-up.    await runInDurableObject(stub, (instance: Business) => {      const store = (instance as unknown as { store: { carryCounts(steps: number): boolean } }).store;      for (let i = 0; i < 10_000 && store.carryCounts(100); i++);    });    const fillMs = Date.now() - made;    const start = Date.now();    const took: number[] = [];    const read: number[] = [];    /** Rows read from the rows table itself: what would grow with the held mail. */    const heldRead: number[] = [];    let widest = { rows: 0, query: "" };    let worst = { rows: 0, at: -1, statements: [] as string[] };    for (let i = 0; i < ARRIVING; i++) {      // A fifth are replies into a conversation that arrived earlier this hour.      const root = i >= 10 && i % 5 === 0 ? i - 7 : null;      const raw = message(i, root);      await runInDurableObject(stub, async (instance: Business, state) => {        const sql = state.storage.sql;        const exec = sql.exec.bind(sql);        const seen: { query: string; cursor: SqlStorageCursor<Record<string, SqlStorageValue>> }[] = [];        (sql as unknown as { exec: typeof sql.exec }).exec = ((query: string, ...args: SqlStorageValue[]) => {          const cursor = exec(query, ...args);          seen.push({ query, cursor });          return cursor;        }) as typeof sql.exec;        const at = performance.now();        try {          await instance.mailArrive({ raw, to: `me@${DOMAIN}`, forwarded: "none", received: start + Math.round((i * HOUR) / ARRIVING) });        } finally {          (sql as unknown as { exec: typeof sql.exec }).exec = exec;        }        took.push(performance.now() - at);        const watched = { statements: seen.map((s) => ({ query: s.query, rowsRead: s.cursor.rowsRead })) };        for (const s of watched.statements) if (s.rowsRead > widest.rows) widest = { rows: s.rowsRead, query: s.query.replace(/\s+/g, " ").slice(0, 140) };        read.push(watched.statements.reduce((n, s) => n + s.rowsRead, 0));        heldRead.push(watched.statements.filter((s) => /\bFROM rows\b/.test(s.query)).reduce((n, s) => n + s.rowsRead, 0));        if (heldRead[heldRead.length - 1]! > worst.rows) worst = { rows: heldRead[heldRead.length - 1]!, at: i, statements: watched.statements.filter((s) => s.rowsRead > 50).map((s) => `${s.rowsRead}: ${s.query.replace(/\s+/g, " ").slice(0, 500)}`) };      });    }    const counts = await runInDurableObject(stub, (_i, state) => ({      emails: Number(state.storage.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows WHERE table_id = 'email'").one().n),      threads: Number(state.storage.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows WHERE table_id = 'email_thread'").one().n),      kept: state.storage.sql.exec<{ kept: string; n: number }>("SELECT kept, COUNT(*) AS n FROM mail_arrival GROUP BY kept").toArray(),    }));    const sorted = [...took].sort((a, b) => a - b);    const p = (q: number) => Math.round(sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]!);    const tallyAt = performance.now();    const tally = await http<{ days: { came: number }[] }>(SLUG, "GET", "/v1/mail/tally?days=2", undefined, auth);    const tallyMs = Math.round(performance.now() - tallyAt);    console.log(      `own-mail big: held ${HELD} mails in ${HELD_THREADS} conversations (filled in ${fillMs} ms); ${ARRIVING} arriving; object ms per arrival p50 ${p(0.5)} p95 ${p(0.95)} max ${p(1)}; rows read per arrival max ${Math.max(...read)}, of the rows table ${Math.max(...heldRead)} (widest statement ${widest.rows}: ${widest.query}); tally ${tallyMs} ms; kept ${JSON.stringify(counts.kept)}`,    );    console.log(`own-mail big, the arrival that read the most (number ${worst.at}, ${worst.rows} rows of the rows table):\n  ${worst.statements.join("\n  ")}`);    const replies = Array.from({ length: ARRIVING }, (_, i) => i).filter((i) => i >= 10 && i % 5 === 0).length;    expect(counts.emails).toBe(HELD + ARRIVING);    expect(counts.threads).toBe(HELD_THREADS + ARRIVING - replies);    expect(counts.kept).toEqual([{ kept: "rows", n: ARRIVING }]);    expect(tally.body.days.reduce((n, d) => n + d.came, 0)).toBe(ARRIVING);    // What an arrival reads does not grow with what is held: never a scan of the held mail.    expect(Math.max(...heldRead)).toBeLessThan(100);    // An hour's 500 are one each 7 seconds; the middle arrival must be well inside that, on a busy machine too.    expect(p(0.5)).toBeLessThan(5_000);  });});