test(supabase): V1-2.1 re-runnable sandbox suite, two-session cases, caps timing
F18 and workspaces no longer leave the seed owner changed. Ten two-session scenarios with a blocking session, seed-owner AR-1 acceptance, shim columns against the image, save/submit/approve/publish timed at the caps.
This commit is contained in:
1 parent
d05f75da84
commit
ef1f4b593f
10 files changed
+930
-65
No files matched your search
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* Fixtures of the V1-2.1 sheet suites on the throwaway stack (real GoTrue,
|
||||
* PostgREST, Storage and PostgreSQL): accounts at aal2 holding a platform role
|
||||
* and catalogue rights, an official sheet whose drawing goes through the
|
||||
* Storage INSERT policy, the verdict written by a postgres session standing in
|
||||
* for the worker of M6 (contract §12.2), and a blocking session that makes two
|
||||
* calls queue on one lock in a known order (contract §15, two sessions).
|
||||
*/
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { confirmedAccount, rpc, sql, stack, type RestResult } from './stack'
|
||||
import { steppedUp, type SteppedAccount } from './mfa'
|
||||
|
||||
export type GrantKind = 'catalog_reader' | 'sheet_editor' | 'sheet_reviewer' | 'sheet_publisher'
|
||||
|
||||
/** A confirmed account at aal2 with an optional platform role and catalogue rights (written as postgres). */
|
||||
export async function holder(
|
||||
tag: string,
|
||||
role: 'owner' | 'admin' | null,
|
||||
grants: GrantKind[],
|
||||
): Promise<SteppedAccount> {
|
||||
const account = await steppedUp(await confirmedAccount(tag))
|
||||
if (role) await sql(`select private.assign_platform_role(null, '${account.id}', '${role}')`)
|
||||
for (const kind of grants)
|
||||
await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
|
||||
values ('${account.id}', '${kind}', 'sandbox', ${kind === 'catalog_reader' ? 'null' : "'sandbox'"}, '${account.id}')`)
|
||||
return account
|
||||
}
|
||||
|
||||
/** The message (closed code) of a refused call, or null for a success. */
|
||||
export const message = (result: RestResult): string | null =>
|
||||
result.status === 200 ? null : ((result.body as { message?: string }).message ?? result.text)
|
||||
|
||||
/** The body of a successful call; throws with the answer otherwise. */
|
||||
export function ok(result: RestResult): unknown {
|
||||
if (result.status !== 200) throw new Error(`HTTP ${result.status}: ${result.text}`)
|
||||
return result.body
|
||||
}
|
||||
|
||||
/** A one-view, one-zone document whose three status-bearing elements are reviewed. */
|
||||
export function sheetDoc(asset: string | null, description = 'd'): Record<string, unknown> {
|
||||
const name = (fr: string) => ({ fr, en: fr })
|
||||
return {
|
||||
schema_version: 2,
|
||||
species_id: 'equine',
|
||||
name: name('Cheval sandbox'),
|
||||
description: name(description),
|
||||
scope_disclaimer: name('x'),
|
||||
attribution: { authors: ['F'], license: null, notes: null },
|
||||
vertebral_config: { regions: [] },
|
||||
references: [],
|
||||
categories: [{ id: 'c', name: name('C'), color: null }],
|
||||
views: [{ id: 'main', kind: 'main', name: name('V'), svg_asset_id: asset, view_box: null }],
|
||||
annotations: [{
|
||||
id: 'a1', kind: 'point', view_id: 'main', category_id: 'c', laterality: 'unpaired', geometry: null,
|
||||
review_status: 'reviewed', name: name('P'), finding_zone_id: 'z1', vertebral_region_code: null,
|
||||
}],
|
||||
finding_zones: [{
|
||||
id: 'z1', name: name('Z'),
|
||||
categories: [{
|
||||
id: 'cat', kind: 'dysfunction', name: name('D'), review_status: 'reviewed',
|
||||
children: [{ id: 'n1', name: name('N'), review_status: 'reviewed' }],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/** A distinct small SVG drawing of about `size` bytes. */
|
||||
export function drawing(size = 200): Buffer {
|
||||
const head = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><!-- ${randomUUID()} `
|
||||
const tail = ' --><rect width="10" height="10"/></svg>'
|
||||
return Buffer.from(head + 'x'.repeat(Math.max(0, size - head.length - tail.length)) + tail)
|
||||
}
|
||||
|
||||
export const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')
|
||||
|
||||
/** Uploads `bytes` under their content key through the Storage API; the INSERT policy decides. */
|
||||
export async function upload(token: string, bytes: Buffer): Promise<number> {
|
||||
const res = await fetch(`${stack.storageUrl}/object/anatomical-sheet-assets/${sha256(bytes)}.svg`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'image/svg+xml' },
|
||||
body: new Uint8Array(bytes),
|
||||
})
|
||||
await res.arrayBuffer()
|
||||
return res.status
|
||||
}
|
||||
|
||||
export interface Sheet {
|
||||
id: string
|
||||
draft: string
|
||||
asset: string
|
||||
sha: string
|
||||
}
|
||||
|
||||
/** An official sheet by `editor`: drawing registered, uploaded and confirmed, draft saved reviewed (revision 1). */
|
||||
export async function officialSheet(editor: SteppedAccount, bytes = drawing()): Promise<Sheet> {
|
||||
const slug = `sb-${randomUUID().slice(0, 12)}`
|
||||
const id = ok(await rpc('create_official_sheet', { slug, document: sheetDoc(null) }, editor.aal2)) as string
|
||||
const draft = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${id}' and status = 'draft'`)
|
||||
const sha = sha256(bytes)
|
||||
const asset = ok(await rpc('register_sheet_asset',
|
||||
{ sheet_id: id, sha256: sha, byte_size: bytes.length, file_name: 'd.svg' }, editor.aal2)) as string
|
||||
const uploaded = await upload(editor.aal2, bytes)
|
||||
if (uploaded !== 200) throw new Error(`upload: HTTP ${uploaded}`)
|
||||
ok(await rpc('confirm_sheet_asset_upload', { asset_id: asset }, editor.aal2))
|
||||
ok(await rpc('save_sheet_draft',
|
||||
{ version_id: draft, expected_revision: 0, document: sheetDoc(asset), change_note: 'wire' }, editor.aal2))
|
||||
return { id, draft, asset, sha }
|
||||
}
|
||||
|
||||
export const GROUP_KEYS = ['general', 'view:main', 'zone:z1']
|
||||
|
||||
/** The worker's stand-in: a passing verdict on the round, which opens (§6.4). */
|
||||
export async function openRound(review: string, sheet: Sheet): Promise<void> {
|
||||
const verdict = {
|
||||
fingerprint: 'a'.repeat(64),
|
||||
drawings: [{ asset_id: sheet.asset, sha256: sheet.sha }],
|
||||
groups: GROUP_KEYS.map((key) => ({ key, digest: '1'.repeat(64), coverable: true })),
|
||||
}
|
||||
await sql(`update public.anatomical_sheet_reviews set status = 'open', verified_at = now(), verified_with = 'sandbox',
|
||||
verdict = '${JSON.stringify(verdict)}'::jsonb where id = '${review}'`)
|
||||
}
|
||||
|
||||
/** `editor` submits the draft at `revision`, the round opens, `reviewer` acknowledges every group. */
|
||||
export async function openRoundAcknowledged(
|
||||
editor: SteppedAccount,
|
||||
reviewer: SteppedAccount,
|
||||
sheet: Sheet,
|
||||
revision = 1,
|
||||
): Promise<string> {
|
||||
const review = ok(await rpc('submit_sheet_review',
|
||||
{ version_id: sheet.draft, expected_revision: revision, note: 'round' }, editor.aal2)) as string
|
||||
await openRound(review, sheet)
|
||||
for (const key of GROUP_KEYS)
|
||||
ok(await rpc('acknowledge_sheet_review_group',
|
||||
{ review_id: review, group_key: key, group_digest: '1'.repeat(64) }, reviewer.aal2))
|
||||
return review
|
||||
}
|
||||
|
||||
/** As openRoundAcknowledged, then `reviewer` approves. */
|
||||
export async function approvedRound(
|
||||
editor: SteppedAccount,
|
||||
reviewer: SteppedAccount,
|
||||
sheet: Sheet,
|
||||
revision = 1,
|
||||
): Promise<string> {
|
||||
const review = await openRoundAcknowledged(editor, reviewer, sheet, revision)
|
||||
ok(await rpc('decide_sheet_review', { review_id: review, approve: true, note: 'ok' }, reviewer.aal2))
|
||||
return review
|
||||
}
|
||||
|
||||
/** Polls `query` (a boolean select) until it answers true. */
|
||||
async function until(query: string, what: string, timeoutMs = 10_000): Promise<void> {
|
||||
const end = Date.now() + timeoutMs
|
||||
while (Date.now() < end) {
|
||||
if ((await sql(query)) === 't') return
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
}
|
||||
throw new Error(`timeout waiting for ${what}`)
|
||||
}
|
||||
|
||||
/** Once a session named `tag` sleeps (it holds its lock). */
|
||||
export const sessionHolds = (tag: string) =>
|
||||
until(`select exists (select 1 from pg_stat_activity where application_name = '${tag}'
|
||||
and wait_event = 'PgSleep')`, `${tag} to hold its lock`)
|
||||
|
||||
/** Once a session named `tag` waits on a lock. */
|
||||
export const sessionWaits = (tag: string) =>
|
||||
until(`select exists (select 1 from pg_stat_activity where application_name = '${tag}'
|
||||
and wait_event_type = 'Lock')`, `${tag} to wait on a lock`)
|
||||
|
||||
/** Once `n` API calls of `fn` wait on a lock. */
|
||||
export const callsWait = (fn: string, n = 1) =>
|
||||
until(`select count(*) >= ${n} from pg_stat_activity where wait_event_type = 'Lock'
|
||||
and query like '%${fn}%' and application_name not like 'sandbox-%'`, `${n} ${fn} call(s) to queue`)
|
||||
|
||||
/** A postgres session named `tag` running `body` (statements) inside one transaction. */
|
||||
export const session = (tag: string, body: string): Promise<string> =>
|
||||
sql(`set application_name = '${tag}'; begin; ${body}; commit;`)
|
||||
|
||||
export type Call = [fn: string, run: () => Promise<RestResult>]
|
||||
|
||||
/**
|
||||
* Holds `lock` in a blocking session, fires `first` and waits until it queues,
|
||||
* fires `second` and waits until it queues too, then lets the lock go: the two
|
||||
* calls meet the contended lock in that order. Fails if either call does not
|
||||
* queue (the lock it should take is not the one held).
|
||||
*/
|
||||
export async function inOrder(lock: string, first: Call, second: Call): Promise<[RestResult, RestResult]> {
|
||||
const tag = `sandbox-blocker-${randomUUID().slice(0, 8)}`
|
||||
const blocker = session(tag, `${lock}; select pg_sleep(3)`)
|
||||
await sessionHolds(tag)
|
||||
const a = first[1]()
|
||||
await callsWait(first[0])
|
||||
const b = second[1]()
|
||||
await callsWait(second[0], first[0] === second[0] ? 2 : 1)
|
||||
await blocker
|
||||
return Promise.all([a, b])
|
||||
}
|
||||
Reference in new issue
Block a user