Something went wrong. Try again.
Monorepo for Tangled forked from tangled.org/core
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268import { test, type Browser, type BrowserContext, type Page, type Request, type Route} from "@playwright/test";
import { authFile, isSeeded, type Account } from "./config";import { parseBody, sleep, type Reply } from "./net";import { watchBrowser } from "./record";import { logIn, mintSession } from "./signin";import type { Slot } from "./vocabulary";
interface Write { method: Held["method"]; collection: string; host: string; body: any; route: Route;}
export interface Held { method: "create" | "put" | "delete"; // the knot and the pds take the same xrpc, so the host is what tells them apart host: string; body: any; release: () => Promise<Reply>;}
const SETTLE_MS = 100;
const PATCH = "org.tangled.review.patch";const SUBMIT_PATCH = "org.tangled.review.submitPatch";
const holdWrites = async (where: Page | BrowserContext) => { const parked: Write[] = []; const waiting: (() => void)[] = []; // a parked write is the test's to release, so it doesn't count as busy const inflight = new Map<Request, number>(); // playwright sometimes never reports a request as finished, so an old one stops counting as busy const STALE_MS = 10_000; const busy = () => [...inflight].filter(([, began]) => Date.now() - began < STALE_MS); // these can't lead to a write, so they don't hold the page busy const passive = new Set(["image", "font", "media", "stylesheet"]); // only code under /src writes records, so this traffic can linger const background = [ "/_internal/indexnow", "deliberi", "searchActorsTypeahead", "/node_modules/" ]; where.on("request", (request) => { const url = request.url(); if (passive.has(request.resourceType()) || background.some((part) => url.includes(part))) return; inflight.set(request, Date.now()); }); where.on("requestfinished", (request) => inflight.delete(request)); where.on("requestfailed", (request) => inflight.delete(request));
const park = (route: Route, method: Held["method"], collection?: string) => { inflight.delete(route.request()); const host = new URL(route.request().url()).host; const body = route.request().postDataJSON(); parked.push({ method, collection: collection ?? body.collection, host, body, route }); waiting.splice(0).forEach((wake) => wake()); }; for (const method of ["create", "put", "delete"] as const) await where.route(`**/xrpc/com.atproto.repo.${method}Record`, (route) => park(route, method) ); // patches use their own xrpc, so the createRecord route above never sees them await where.route(`**/xrpc/${SUBMIT_PATCH}`, (route) => park(route, "create", PATCH));
const describe = (w: Write) => `${w.method} ${w.collection} to ${w.host}`;
const next = async ( collection: string, timeout = 10_000, matching?: (body: any) => boolean ): Promise<Held> => { const deadline = Date.now() + timeout; for (;;) { const at = parked.findIndex( (w) => w.collection === collection && (!matching || matching(w.body)) ); if (at >= 0) { const { method, host, body, route } = parked.splice(at, 1)[0]; return { method, host, body, release: async () => { const response = await route.fetch(); const text = await response.text(); // the page always gets the real answer, failing it is the test's job await route.fulfill({ response }); return { status: response.status(), body: parseBody(text) }; } }; } const left = deadline - Date.now(); if (left <= 0) { const held = parked.map(describe).join(", ") || "nothing"; const which = matching ? " that matched" : ""; throw new Error( `no write to ${collection}${which} was sent, the page sent: ${held}` ); } await new Promise<void>((wake) => { waiting.push(wake); setTimeout(wake, left); }); } };
const expectNoOthers = () => { if (parked.length) throw new Error(`the page also sent: ${parked.map(describe).join(", ")}`); };
// the dev server compiles modules as pages ask, so a write can come late under parallel workers const quiet = async (silence = 500, limit = 20_000) => { const deadline = Date.now() + limit; let since = Date.now(); while (Date.now() < deadline && Date.now() - since < silence) { await sleep(50); if (busy().length) since = Date.now(); } if (Date.now() - since < silence) { throw new Error( `the page still had a request running after ${limit / 1000}s, so nothing can be said about what it sends next: ${busy() .map(([request]) => request.url()) .join(", ")}` ); } };
const sent = (collection: string) => parked.some((w) => w.collection === collection);
return { next, expectNoOthers, quiet, sent };};
interface Tab { context: BrowserContext; windows: Map<string, Page>; writes: Awaited<ReturnType<typeof holdWrites>>; held: Map<Slot, Held>; devices: BrowserContext[];}
export class Tabs { private tabs = new Map<string, Tab>();
constructor(private browser: Browser) {}
private of(account: Account) { const tab = this.tabs.get(account.name); if (!tab) throw new Error(`${account.name} has no browser yet, start with an .open()`); return tab; }
page(account: Account, window = "") { const page = this.of(account).windows.get(window); if (!page) throw new Error(`${account.name} has no window ${window}, start with a .window()`); return page; }
async openWindow(account: Account, window: string) { const tab = this.of(account); if (!tab.windows.has(window)) tab.windows.set(window, await tab.context.newPage()); }
// another browser signed in as the same account, sharing no storage with the first async openDevice(account: Account, window: string) { const tab = this.of(account); if (tab.windows.has(window)) return; const context = await this.browser.newContext({ storageState: await this.signedIn(account, false) }); watchBrowser(context); tab.devices.push(context); tab.windows.set(window, await context.newPage()); }
private signedIn(account: Account, throughThePage: boolean) { if (isSeeded(account)) return authFile(account); if (throughThePage) return undefined; return test.step("mint a session", () => mintSession(account)); }
async open(account: Account, throughThePage: boolean) { if (this.tabs.has(account.name)) return; const storageState = await this.signedIn(account, throughThePage); const context = await this.browser.newContext({ storageState }); watchBrowser(context); const page = await context.newPage(); const writes = await holdWrites(context); this.tabs.set(account.name, { context, windows: new Map([["", page]]), writes, held: new Map(), devices: [] }); if (!isSeeded(account) && throughThePage) await test.step("log in through the login page", () => logIn(page, account)); }
// a slot already holding a write answers with that one, whatever it is asked to match async hold(account: Account, slot: Slot, matching?: (body: any) => boolean) { const tab = this.of(account); let held = tab.held.get(slot); if (!held) { held = await tab.writes.next(slot.nsid, undefined, matching); tab.held.set(slot, held); } return held; }
async release(account: Account, slot: Slot, held: Held, expected: number | number[] = 200) { const reply = await held.release(); this.of(account).held.delete(slot); if (![expected].flat().includes(reply.status)) { throw new Error( `${held.method} ${slot.nsid} answered ${reply.status} ${JSON.stringify(reply.body)}, expected ${expected}` ); } return reply.body; }
// playwright's own networkidle always waits 500ms, which every open and reload would pay async settle(account: Account) { await this.of(account).writes.quiet(SETTLE_MS); }
async expectNoWrite(account: Account, slot: Slot) { const { writes } = this.of(account); await writes.quiet(); if (writes.sent(slot.nsid)) throw new Error(`the page sent a write to ${slot.nsid}`); }
async expectQuiet() { const tabs = [...this.tabs.values()]; for (const tab of tabs) { const [unreleased] = tab.held.keys(); if (unreleased) { throw new Error( `the page sent a write to ${unreleased.nsid} that no .trace() let through` ); } } // wait on every tab before judging any, or a late write from one slips past await Promise.all(tabs.map((tab) => tab.writes.quiet())); for (const tab of tabs) tab.writes.expectNoOthers(); }
async close() { for (const tab of this.tabs.values()) { for (const context of [tab.context, ...tab.devices]) await context.close().catch(() => {}); } }}