import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { fr } from '@/i18n/fr' import type { Locator, Page } from '@playwright/test' import { rpc, sql, stack, } from '../../../../packages/supabase/tests/sandbox/stack' import { stepUpAdmin } from '../support/admin' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { place, type Actor, closeReferences, editorActor, openEditor, openReferences, openSection, SECTIONS, seedDraft, selectTab, serverDocument, showDrawing, standardShape, toolButton, } from '../support/editor' import { signIn } from '../support/shell' // V1-2.6 equine working copy and commit latency (contract C31, plan « Edge cases »): the // historical equine sheet opened as a working copy in the editor (a copy left active by // an earlier run is set aside first, as sheets-concurrency.sandbox.ts does), the commit // latency measured on it and on a synthetic document near 2 MiB. The numbers are // reported (console, test annotations); the budget is 500 ms per commit on the equine copy. const dict = fr const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916' const REPO = join(__dirname, '../../../..') const BUDGET_MS = 500 const SAMPLES = 15 interface Sample { handler: number paint: number } /** Time from the Enter or click that commits to the end of its task, and to the 2nd frame. */ async function startProbe(page: Page) { await page.evaluate(() => { const w = window as unknown as { __latency?: Sample[] } if (w.__latency) { w.__latency.length = 0 return } const samples: Sample[] = [] w.__latency = samples const mark = (event: Event) => { const start = performance.now() setTimeout(() => { const handler = performance.now() - start requestAnimationFrame(() => requestAnimationFrame(() => samples.push({ handler, paint: performance.now() - start }), ), ) }, 0) void event } window.addEventListener( 'keydown', (e) => e.key === 'Enter' && mark(e), true, ) window.addEventListener('click', mark, true) }) } function takeSamples(page: Page): Promise { return page.evaluate(() => { const w = window as unknown as { __latency: Sample[] } return w.__latency.splice(0) }) } function stats(values: number[]) { const sorted = [...values].sort((a, b) => a - b) const at = (share: number) => sorted[Math.floor(share * (sorted.length - 1))] return { n: sorted.length, median: Math.round(at(0.5)), p95: Math.round(at(0.95)), max: Math.round(sorted[sorted.length - 1]), } } function report(label: string, samples: Sample[]) { const line = { label, handler: stats(samples.map((s) => s.handler)), paint: stats(samples.map((s) => s.paint)), } console.log(`LATENCY ${JSON.stringify(line)}`) test.info().annotations.push({ type: 'latency', description: JSON.stringify(line), }) return line } async function commitName(field: Locator, round: number) { await field.fill(`Nom mesuré ${round}`) await field.press('Enter') } /** SAMPLES commits of the sheet's French name, one probe entry each (after a warm-up). */ async function measureRenames(page: Page, label: string) { await selectTab(page, dict, 'general') const field = place(page, 'general').getByLabel( dict['editor.general.name_fr'], { exact: true }, ) await startProbe(page) await commitName(field, 0) await takeSamples(page) for (let round = 1; round <= SAMPLES; round++) await commitName(field, round) await expect(field).toHaveValue(`Nom mesuré ${SAMPLES}`) await page.waitForTimeout(200) return report(label, await takeSamples(page)) } async function measureAdditions(page: Page, label: string) { await openSection(page, dict, 'categories') await startProbe(page) for (let round = 0; round <= SAMPLES; round++) { await page.locator('#category-new-fr').fill(`Catégorie ${round}`) await page.locator('#category-new-en').fill(`Category ${round}`) await page.locator('#category-new-fr').press('Tab') await page .getByRole('button', { name: dict['editor.general.category_add'] }) .click() await expect(page.locator('#category-new-fr')).toHaveValue('') } await page.waitForTimeout(200) // The first round is the warm-up. return report(label, (await takeSamples(page)).slice(1)) } async function confirmHistoricalDrawing() { const row = ( await sql(`select id || ' ' || sha256 || ' ' || (uploaded_at is null)::text from public.anatomical_sheet_assets where sheet_id = '${HISTORICAL}'`) ).split(' ') if (row[2] !== 'true') return const bytes = await readFile( join(REPO, 'supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg'), ) const stored = await fetch( `${stack.storageUrl}/object/anatomical-sheet-assets/${row[1]}.svg`, { method: 'POST', headers: { Authorization: `Bearer ${stack.serviceKey}`, 'Content-Type': 'image/svg+xml', }, body: new Uint8Array(bytes), }, ) await stored.arrayBuffer() const confirmed = await rpc( 'confirm_sheet_asset_upload', { asset_id: row[0] }, stack.serviceKey, ) expect(confirmed.status).toBe(200) } /** Finding nodes with long descriptions, up to about 1.9 MiB of document text. */ function nearCapShape(document: Record) { standardShape(document) const filler = (letter: string) => letter.repeat(260) const zones = [] for (let z = 0; z < 20; z++) { const categories = [] for (let c = 0; c < 10; c++) { const children = [] for (let n = 0; n < 12; n++) { children.push({ id: `node-${z}-${c}-${n}`, name: { fr: `Constat ${z}.${c}.${n}`, en: `Finding ${z}.${c}.${n}` }, description: { fr: filler('a'), en: filler('b') }, requires_vet_referral: false, reference_ids: [], review_status: 'reviewed', children: [], }) } categories.push({ id: `fcat-${z}-${c}`, kind: 'dysfunction', name: { fr: `Catégorie ${z}.${c}`, en: `Category ${z}.${c}` }, description: {}, reference_ids: [], review_status: 'reviewed', children, }) } zones.push({ id: `zone-${z}`, name: { fr: `Zone ${z}`, en: `Zone ${z}` }, categories, }) } document.finding_zones = zones } test.describe.configure({ mode: 'serial' }) test.describe('equine working copy and commit latency', () => { test.use({ locale: 'fr-FR', actionTimeout: 30_000 }) // Skipped as a whole on the phone project: beforeAll and afterAll toggle the copies' // status and must run in one worker only. test.skip(({ isMobile }) => isMobile, 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access let actor: Actor let setAside: string[] = [] let copyId = '' test.beforeAll(async () => { actor = await editorActor('fr') await confirmHistoricalDrawing() // A copy left active by an earlier run is set aside and put back after. setAside = ( await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now() where status = 'active' and private.is_historical_working_copy(id) returning id`) ) .split('\n') .filter(Boolean) }) test.afterAll(async () => { // Archived as postgres, like the set-aside below: the sheet is a fixture of this run. if (copyId) await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now() where id = '${copyId}'`) if (setAside.length > 0) await sql(`update public.anatomical_sheets set status = 'active', archived_at = null where id in (${setAside.map((id) => `'${id}'`).join(', ')})`) }) test.beforeEach(async ({ context }) => { await routeToSandbox(context) }) test.afterEach(async ({ context }) => { await dropLateReplays(context) }) test('the historical equine sheet opens as a working copy in the editor', async ({ page, requests, }) => { test.setTimeout(120_000) requests.forbid(actor.account.email, actor.account.password) const errors: string[] = [] page.on('pageerror', (error) => errors.push(error.message)) await signIn(page, actor.account, dict) await page.goto('/app/admin') await stepUpAdmin(page, dict, actor.secret) await page.goto(`/app/admin/sheets/${HISTORICAL}`) await page .getByRole('button', { name: dict['admin.working_copy.create'] }) .first() .click() const dialog = page.getByRole('dialog', { name: dict['admin.working_copy.create'], }) // The proposed slug is taken by the copies of earlier runs: one of its own. await dialog .getByLabel(dict['admin.sheet_form.slug']) .fill(`e2e-copie-${actor.account.id.slice(0, 8)}`) await dialog .getByRole('button', { name: dict['admin.working_copy.confirm'] }) .click() await expect(page).toHaveURL(/\/app\/admin\/sheets\/[0-9a-f-]{36}\/draft$/) copyId = new URL(page.url()).pathname.split('/')[4] await expect( page.getByText(dict['admin.badge.working_copy'], { exact: true }), ).toBeVisible() await expect(toolButton(page, dict, 'point')).toBeEnabled() const rows = page .getByRole('list', { name: dict['editor.annotations.list'] }) .getByRole('listitem') await expect(rows.first()).toBeVisible() expect(await rows.count()).toBeGreaterThan(5) await expectAccessible(page, 'the equine working copy') // Every tab opens on the real equine data without a page error (the findings tree // once blanked the page on nodes that omit their defaulted fields). await selectTab(page, dict, 'findings') await expect(page.getByTestId('finding-item').first()).toBeVisible() for (const tab of ['general', 'verification']) await selectTab(page, dict, tab) for (const section of SECTIONS) await openSection(page, dict, section) await openReferences(page, dict) await closeReferences(page, dict) expect(errors, 'page errors on the equine copy').toEqual([]) }) test('commit latency on the equine copy', async ({ page, requests }) => { test.setTimeout(180_000) expect(copyId).not.toBe('') requests.forbid(actor.account.email, actor.account.password) await signIn(page, actor.account, dict) await page.goto('/app/admin') await stepUpAdmin(page, dict, actor.secret) await page.goto(`/app/admin/sheets/${copyId}/draft`) await expect(toolButton(page, dict, 'point')).toBeEnabled() const renames = await measureRenames(page, 'equine: rename (update)') const additions = await measureAdditions( page, 'equine: add category (insert)', ) // A geometry edit: the first annotation's centre, through the geometry group. await showDrawing(page, dict) await page .getByRole('list', { name: dict['editor.annotations.list'] }) .getByRole('button') .first() .click() const cx = page.getByLabel(dict['editor.annotations.geometry.cx'], { exact: true, }) const base = Number(await cx.inputValue()) await startProbe(page) for (let round = 0; round <= SAMPLES; round++) { await cx.fill(String(base + ((round % 2) + 1) * 0.5)) await cx.press('Enter') } await page.waitForTimeout(200) const moves = report( 'equine: geometry edit', (await takeSamples(page)).slice(1), ) for (const line of [renames, additions, moves]) expect(line.handler.max, line.handler.max + ' ms').toBeLessThan(BUDGET_MS) }) test('commit-to-paint on the equine copy with every place visited (U1 shell)', async ({ page, requests, }) => { test.setTimeout(180_000) expect(copyId).not.toBe('') requests.forbid(actor.account.email, actor.account.password) await signIn(page, actor.account, dict) await page.goto('/app/admin') await stepUpAdmin(page, dict, actor.secret) await page.goto(`/app/admin/sheets/${copyId}/draft`) await expect(toolButton(page, dict, 'point')).toBeEnabled() // Every tab, section and the panel mounted once: all of them stay mounted (B2a). for (const tab of ['general', 'findings', 'verification']) await selectTab(page, dict, tab) for (const section of SECTIONS) await openSection(page, dict, section) await openReferences(page, dict) await closeReferences(page, dict) const renames = await measureRenames(page, 'equine, all places: rename') const additions = await measureAdditions(page, 'equine, all places: add') for (const line of [renames, additions]) expect(line.paint.max, `${line.paint.max} ms to paint`).toBeLessThan( BUDGET_MS, ) }) test('commit latency on a synthetic document near 2 MiB', async ({ page, requests, }) => { test.setTimeout(180_000) requests.forbid(actor.account.email, actor.account.password) const seed = await seedDraft(actor, { shape: nearCapShape }) const bytes = Number( await sql( `select octet_length(content::text) from public.anatomical_sheet_versions where id = '${seed.draftId}'`, ), ) console.log(`SYNTHETIC document ${bytes} bytes`) expect(bytes).toBeGreaterThan(1_800_000) expect(bytes).toBeLessThanOrEqual(2_097_152) expect( Object.keys(await serverDocument(seed.draftId)).length, ).toBeGreaterThan(5) await openEditor(page, dict, actor, seed.sheetId) const renames = await measureRenames( page, `synthetic ${bytes} B: rename (update)`, ) const additions = await measureAdditions( page, `synthetic ${bytes} B: add category (insert)`, ) test.info().annotations.push({ type: 'synthetic-bytes', description: String(bytes), }) expect(renames.handler.n).toBeGreaterThan(0) expect(additions.handler.n).toBeGreaterThan(0) }) })