diff --git a/docs/specs/access.md b/docs/specs/access.md index 6175a6c..8897f6f 100644 --- a/docs/specs/access.md +++ b/docs/specs/access.md @@ -36,6 +36,7 @@ Every project here is public, and one person writes (rationale). - **Must know the writer by their GitHub account's numeric ID, never their login**, which can be renamed and taken by someone else. - **Must sign anyone else straight back out when GitHub returns them**, and never treat their session as the writer's (rationale). **Must then send them to selfie.dev's mailing list signup, `https://selfie.dev/#join=`, with the verified email GitHub gave, or none**, in the URL's fragment, which a browser never sends to a server or in a `Referer` (rationale). `site/public/join.js` fills the form in and says the cloud isn't open yet, and joining stays their click. - **Must drive the adapter from the Worker, and let nothing outside reach it but GitHub's callback, `GET /api/auth/callback/github`.** Its CSRF token, its sign-in and sign-out writes, and its account list are only ever the Worker's own requests to it, and its email routes are reached by nothing. It's given only its own bindings, and an email sender that sends nothing. +- **Must ask the adapter who a review request is from only where the answer is used: a batch's view, which says whether they may decide, and a decision.** An image, a diff, and every other read never reach it (rationale). - **Must refuse a sign-in or sign-out from another site, and send a person only to a path on this site after signing in**, held in a 10-minute `__Host-` cookie, since the adapter returns everyone to one fixed path. - **Must end a sign-in GitHub or the adapter failed at `/sign-in?failed=`**, logging what the adapter answered under that code, and show the code only if it's one the Worker could have made (`docs/specs/ui.md` → ReviewSource). - **Must keep `sameOriginWrites` and `pageHeaders` on the review routes.** The sync routes answer only to a bearer token, and never read a cookie. @@ -76,7 +77,7 @@ GitHub decides. Selfie keeps no member list of its own. ### Serving images - **Never give an image a direct R2 URL.** Every image is served by the Worker after an access check, and the bucket issues no presigned URLs. Its public URLs are already off ([Who can do what](#who-can-do-what)). -- **Never treat an image hash as a secret**, since anyone holding an image can compute it. Access depends on who is asking and which project they ask about. +- **Never treat an image hash as a secret**, since anyone holding an image can compute it. Access depends on who is asking and which project they ask about, which is still never a question to the auth adapter per image ([Who can do what](#who-can-do-what)). - **Must serve images with `Cache-Control: private`, for public repositories too**, since a repository can become private and a shared cache would keep serving it. - **Must serve images with `X-Content-Type-Options: nosniff`, and a type read from their first bytes**, since the cloud doesn't read a file's body (`docs/specs/sync.md` → What a store takes). - **Must rate-limit anonymous requests**, since anyone can make them and each one costs an R2 read. diff --git a/docs/specs/access.rationale.md b/docs/specs/access.rationale.md index 91f862e..fe417b8 100644 --- a/docs/specs/access.rationale.md +++ b/docs/specs/access.rationale.md @@ -34,4 +34,6 @@ **On to the mailing list.** Anyone who gets as far as GitHub's consent screen wants Selfie, and doesn't know who its one writer is, so they're offered the list rather than a refusal. Their address is already in hand, so it's filled in, but in the fragment: a query string would land in Cloudflare's and Pages' logs, and in MailerLite's if the page's own requests carried a `Referer`. The form still needs their click, and MailerLite's double opt-in still applies. +**Asking who it is only where that's used.** Each question is a request to the adapter, which keeps Better Auth's rate limit on, by default 100 requests in 10 seconds from one address. A batch's page asks for a diff and two images for each changed story, 4 at a time, so the 143 stories of PR #108's batch, signed in, asked the adapter over 400 times in a few seconds. Past about 100 it answered 429, those requests failed, and 34 stories were left out of the deltas offered (`docs/specs/ui.md` → Screens). Anyone can read an image or a diff anyway, and a decision asks again for itself, so nothing is lost by not asking. + **An upload token rather than OIDC.** It's a secret a repository has to hold, which OIDC avoids, and it costs a rotation if it leaks. A leak lets someone upload to a public project, which can't approve anything, and can only add batches at commits GitHub has. diff --git a/docs/specs/ui.md b/docs/specs/ui.md index b908fdc..3409360 100644 --- a/docs/specs/ui.md +++ b/docs/specs/ui.md @@ -166,10 +166,11 @@ Source of truth: `ui/src/client/`. - **Must find a delta from a pair's own diff, fetched by both hashes, and never a review's stats** ([Screens](#screens)), since those are by story, and could be of another pair. - **Must group raw hunks, not the groups a list shows, by the size of each side, and then by the SHA-256 of each side's pixels**, wherever in an image a hunk sits (rationale). It decodes only images with a size at least 3 stories share. - **Must key a hunk as `x>x::`, each digest the lowercase hex SHA-256 of that side's pixels as RGB row by row, as the store has them, or empty for a side with no pixels**, through `hunkKeysOf`, so Node and a browser give one pair the same keys (rationale). A key accepted before keys were RGB matches no hunk, and is ignored. -- **Must use pixels a browser decoded only if they hash to the image they were fetched by**, as the store computes an image's hash (`docs/specs/store.md` → Image identity). A pair either of whose images doesn't is one that can't be looked at, so it's in no delta (rationale). +- **Must use pixels a browser decoded only if they hash to the image they were fetched by**, as the store computes an image's hash (`docs/specs/store.md` → Image identity). A pair either of whose images doesn't is one that can't be looked at, so it's in no delta, and counts among the stories it couldn't look at, without being tried again (rationale). - **Must only group a hunk that can be redrawn on its own:** one with the same size on both sides, or one the whole width of both images. A narrower hunk that changes height only balances out with others in its column, so it stays a hunk to look at. - **Must grow a delta, and never merge two:** once all are hashed, a straggler, which is a hunk whose pixels fewer than 3 stories have, joins the first delta of its size whose own pixels it's within a level of in every channel, on both sides (rationale). Deltas are tried most stories first, counting every story whatever's decided, so what a hunk joins doesn't change as images are approved. Only a hunk of at most `MAX_FIT_AREA` pixels, both sides together, is fitted, each story's images are decoded once for all of its hunks being fitted, and a delta's own pixels are held only while fitting. - **Must say which stories only fit a delta**, by how many beside its count, and on each as it's gone through, and list them after the stories that are exactly its pixels. +- **Must try a story again when the server or the connection refused it**, which is a 429, a 5xx, or no answer: twice more, after half a second and then two. **Must say how many changed stories it still couldn't look at, with a way to look again**, so what's offered never reads as all there is (rationale). Looking again keeps whatever it found. - **Must offer each delta at least 3 undecided changed stories have**, most stories first, once all of them have been looked through, each with how many stories and a crop of it before and after. An image with a decision isn't affected. - **Must let someone go through a delta's stories before accepting it**, one delta at a time, starting with the first and moving on once it's accepted: previous and next through its stories, wrapping around, naming each with a link to it, and showing that story's crop and all of its image on each side as it is on record, with the delta outlined where that story has it (rationale). - **Must say what's accepted, and let each be undone**, which brings its hunks back, the ones that joined it too, and takes back no approval. Accepting holds the key of every hunk it covers, so a story's page redraws the ones that joined it too, wherever it's opened. diff --git a/docs/specs/ui.rationale.md b/docs/specs/ui.rationale.md index 6f0b8ee..d13b894 100644 --- a/docs/specs/ui.rationale.md +++ b/docs/specs/ui.rationale.md @@ -37,6 +37,8 @@ Evidence and reasoning for `docs/specs/ui.md`, keyed by its headings. **Repeated changes, in the browser.** A header that grew 15 rows made all 124 stories of one batch change, and each had to be looked at for whatever else was in it. Of 146 distinct hunks there, 28 were in at least 3 stories, and those accounted for all of 83 images. Whether accepting one should outlive a batch, or be something a team shares, is what **Scope: hunks** in `docs/specs/renders.md` is for. Nothing here narrows that, since a store only ever hears of an approval of a whole image. +**Saying what it couldn't look at.** Looking costs a request per pair's diff and two images each, so a batch of 143 changed stories makes over 400 requests. Signed in to the cloud, each once asked the auth adapter who was asking, its rate limit refused some, and 34 stories were left out of every delta without a word while the progress bar said done (`docs/specs/access.md` → Who can do what). That's fixed at the server, but anything else that refuses a few in a burst would do the same, and a delta that's missing stories looks no different from one that isn't. A 404 or an image that won't decode is never tried again, since it won't change, but it's still counted. + **Why say what was approved earlier.** A merged pull request's commit reads as nothing differing, since its approvals are what it's compared with, which is right for what blocks it and hides what it did. It's found on the page, instead of on the batch that was approved, since that's where a link from a commit lands, and nothing else leads from a later commit to an earlier batch. **Why say what changed since the base, approved or not.** Someone following a commit's status from GitHub wants to know what it changed. What's left to decide on is something else: it leaves out what was approved on an earlier commit, and takes in whatever its base never approved. A decision on a row goes to the batch's own row for the same image, since that's what the store decides on, and a row approved on another batch has nothing left to decide here. diff --git a/ui/src/client/BatchScreen.stories.tsx b/ui/src/client/BatchScreen.stories.tsx index e92dc1f..9ba342f 100644 --- a/ui/src/client/BatchScreen.stories.tsx +++ b/ui/src/client/BatchScreen.stories.tsx @@ -130,6 +130,7 @@ export const ChangesApprovedEarlier: Story = { args: { view: viewOf([]), state: export const ChangesApprovedEarlierListed: Story = { args: { view: viewOf([]), state: { approvedSince: APPROVED_EARLIER }, search: "?show=approved-earlier" } }; export const LookingForRepeatedChanges: Story = { args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ progress: 40 }) } }; export const RepeatedChanges: Story = { args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ offers: OFFERS }) } }; +export const RepeatedChangesNotAllLookedAt: Story = { args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ offers: OFFERS.slice(1), missed: 34 }) } }; export const LookingThroughADelta: Story = { args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ offers: OFFERS }) }, play: async ({ canvasElement }) => { diff --git a/ui/src/client/DeltaOffers.tsx b/ui/src/client/DeltaOffers.tsx index afce9a3..25bd892 100644 --- a/ui/src/client/DeltaOffers.tsx +++ b/ui/src/client/DeltaOffers.tsx @@ -1,5 +1,5 @@ // The changes that repeat across stories, to accept once instead of looking at each. -import { Button, Details, Heading, ProgressBar, Stack, Text, useDetails } from "@primer/react"; +import { Banner, Button, Details, Heading, ProgressBar, Stack, Text, useDetails } from "@primer/react"; import { ScrollableRegion } from "@primer/react/experimental"; import { useState, type ReactNode } from "react"; import type { RenderRow } from "../shared/api.ts"; @@ -191,7 +191,7 @@ function AcceptedDeltas({ deltas }: { deltas: DeltaState }) { export function DeltaOffers({ deltas, state, batchId }: { deltas: DeltaState; state: BatchState; batchId: string }) { const [pending, setPending] = useState<{ readonly delta: Delta; readonly rows: readonly RenderRow[] } | null>(null); const [openKey, setOpenKey] = useState(null); - const { progress, offers, taken } = deltas; + const { progress, missed, offers, taken } = deltas; // One's always open, so accepting one moves on to the next to look at. const open = offers.find(({ key }) => key === openKey) ?? offers[0]; @@ -203,7 +203,7 @@ export function DeltaOffers({ deltas, state, batchId }: { deltas: DeltaState; st ); } - if (offers.length === 0 && taken.length === 0) return null; + if (offers.length === 0 && taken.length === 0 && missed === 0) return null; const pick = (delta: Delta) => { const rows = deltas.finishes(delta); @@ -224,6 +224,14 @@ export function DeltaOffers({ deltas, state, batchId }: { deltas: DeltaState; st Repeated changes + {missed > 0 && ( + Look again} + /> + )} {offers.length > 0 && ( <> diff --git a/ui/src/client/api.ts b/ui/src/client/api.ts index 43abe78..9211daf 100644 --- a/ui/src/client/api.ts +++ b/ui/src/client/api.ts @@ -25,30 +25,49 @@ import { } from "../shared/api.ts"; import { BASE, isHosted } from "./base.ts"; -/** What went wrong, in words a screen can show. `code` tells the cases apart, and `id` is the code the server logged it under, if it did. */ +/** + * What went wrong, in words a screen can show. `code` tells the cases apart, `id` is the code the server logged it under, + * if it did, and `status` is what the server answered, if it did. + */ export class RequestError extends Error { readonly code: string; readonly id: string | null; + readonly status: number | null; - constructor(code: string, message: string, id: string | null = null) { + constructor(code: string, message: string, id: string | null = null, status: number | null = null) { super(message); this.code = code; this.id = id; + this.status = status; } } -async function request(path: string, init?: RequestInit): Promise { - let response: Response; +/** Whether asking again could work: the connection dropped, the server was busy, or something went wrong there. */ +export const mightPassLater = (error: unknown) => error instanceof RequestError && (error.code === "unreachable" || error.status === 429 || (error.status ?? 0) >= 500); + +/** The server's answer, whatever it is, or a `RequestError` saying it couldn't be reached. */ +async function reached(url: string, init?: RequestInit): Promise { try { - response = await fetch(`${BASE}/api${path}`, init); + return await fetch(url, init); } catch (error) { if (init?.signal?.aborted) throw error; throw new RequestError("unreachable", isHosted ? "Can't reach Selfie. Check your connection, and try again." : "Can't reach the Selfie server. Is selfie ui still running?"); } +} + +/** An image's bytes from `imageUrl` or `diffImageUrl`, or a `RequestError` saying what the server answered. */ +export async function fetchImage(url: string): Promise { + const response = await reached(url); + if (!response.ok) throw new RequestError("bad-response", `The server answered ${response.status} for ${url}.`, null, response.status); + return response.blob(); +} + +async function request(path: string, init?: RequestInit): Promise { + const response = await reached(`${BASE}/api${path}`, init); const body = (await response.json().catch(() => null)) as T | ApiError | null; if (!response.ok || body === null) { const error = (body as ApiError | null)?.error; - throw new RequestError(error?.code ?? "bad-response", error?.message ?? `The server answered ${response.status}.`, error?.id ?? null); + throw new RequestError(error?.code ?? "bad-response", error?.message ?? `The server answered ${response.status}.`, error?.id ?? null, response.status); } return body as T; } diff --git a/ui/src/client/deltas.ts b/ui/src/client/deltas.ts index 6eac3dd..b9153ce 100644 --- a/ui/src/client/deltas.ts +++ b/ui/src/client/deltas.ts @@ -27,13 +27,46 @@ import { type ScannedRow, } from "../shared/deltas.ts"; import { fade } from "../shared/diff-image.ts"; -import { diffImageUrl, fetchDiff, imageUrl } from "./api.ts"; +import { diffImageUrl, fetchDiff, fetchImage, imageUrl, mightPassLater } from "./api.ts"; import { useFetched } from "./hooks.ts"; /** Enough to go quickly, and few enough to leave room for whatever else the page is asking for. */ const AT_ONCE = 4; /** Each holds two images, and this is plenty for what's on screen, what's next, and going back a little. */ const PATCHES_KEPT = 16; +/** How long to wait before each further try at what might pass later, after which it's given up on. */ +const RETRY_AFTER_MS = [500, 2_000]; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * Does `work` to each item, a few at a time, trying again whatever might pass later, and gives back each it never + * could, so nothing is left out without a word. Once `stopped`, it starts nothing more. `done` hears what share is through. + */ +export async function workThrough( + items: readonly Item[], + work: (item: Item) => Promise, + { stopped = () => false, done = () => undefined, wait = sleep }: { readonly stopped?: () => boolean; readonly done?: (share: number) => void; readonly wait?: (ms: number) => Promise } = {}, +): Promise { + const failed: Item[] = []; + let through = 0; + await mapConcurrently(items, AT_ONCE, async (item) => { + for (let tries = 0; !stopped(); tries++) { + try { + await work(item); + break; + } catch (error) { + if (tries === RETRY_AFTER_MS.length || !mightPassLater(error)) { + failed.push(item); + break; + } + await wait(RETRY_AFTER_MS[tries]!); + } + } + if (!stopped()) done(++through / items.length); + }); + return failed; +} const pairOf = ({ imageHash, goldenHash }: Comparable) => `${imageHash}/${goldenHash}`; @@ -100,9 +133,7 @@ const knownPatches = new Known(PATCHES_KEPT, ({ images }) => { }); async function decoded(url: string): Promise { - const response = await fetch(url); - if (!response.ok) throw new Error(`The server answered ${response.status} for ${url}.`); - return createImageBitmap(await response.blob(), { colorSpaceConversion: "none", premultiplyAlpha: "none" }); + return createImageBitmap(await fetchImage(url), { colorSpaceConversion: "none", premultiplyAlpha: "none" }); } /** Rows read back from a canvas at once, so a tall image is never held twice over while it's read. Fewer cost WebKit more: at 256, a 2400×9898 image took 2.5 times as long. */ @@ -188,8 +219,11 @@ async function cropsIn(samples: readonly Sample[]): Promise { return withPixels(row, (current, golden) => samples.map(({ index }) => ({ golden: cropOf(golden, hunks[index]!.golden), current: cropOf(current, hunks[index]!.current) }))); } -/** What growing deltas found for one set of pairs, kept so coming back to a batch's screen doesn't decode them again. */ -let grown: { readonly id: string; readonly joins: Joins } | null = null; +/** + * What growing deltas found for the pairs whose hunks are known (`scannedId`), kept so coming back to a batch's screen + * doesn't decode them again, unless some of their images couldn't be. A pair whose diff never came is no reason to grow again. + */ +let grown: { readonly id: string; readonly joins: Joins; readonly whole: boolean } | null = null; const NO_JOINS: Joins = new Map(); /** What each of a story's hunks holds, for saying which are accepted. */ @@ -256,6 +290,10 @@ export function prepareNext(row: RenderRow, accepted: ReadonlySet): void export interface DeltaState { /** How far through looking for them, in percent, or null once that's done. */ readonly progress: number | null; + /** How many changed stories it couldn't look at, even trying again, so what it offers may not be all there is. */ + readonly missed: number; + /** Looks again, at what it couldn't before. */ + readonly retry: () => void; /** Every key accepted, a delta's own and each that joined it (`keysOf`). */ readonly accepted: ReadonlySet; readonly offers: readonly Delta[]; @@ -302,6 +340,8 @@ const scansOf = (pairs: readonly Comparable[]) => return diff === undefined || keys === undefined ? [] : [{ row, diff, keys }]; }); +const scannedId = (scans: readonly ScannedRow[]) => scans.map(({ row }) => pairOf(row)).join(); + /** * Every changed story's hunks and what's in them. `looking` is whether to go on finding that, since * only the batch's own screen shows what it finds, and a story's images come first. What's found stays. @@ -311,6 +351,8 @@ export function useDeltas(batchId: string, rows: readonly RenderRow[] | undefine // How many times it's finished looking, since what it found is in what's known. const [looked, setLooked] = useState(0); const [progress, setProgress] = useState(null); + const [missed, setMissed] = useState(0); + const [tries, setTries] = useState(0); const pairs = useMemo(() => (rows ?? []).filter(isComparable), [rows]); const pairsId = useMemo(() => pairs.map(pairOf).join(), [pairs]); @@ -320,31 +362,33 @@ export function useDeltas(batchId: string, rows: readonly RenderRow[] | undefine return; } let stopped = false; - /** One part of the way there, from one percent to another. A whole percent, so the page only draws again when that changes. One that can't be compared or fitted just can't be part of a delta. */ - const part = async (items: readonly Item[], work: (item: Item) => Promise, from: number, to: number) => { - let done = 0; - await mapConcurrently(items, AT_ONCE, async (item) => { - if (stopped) return; - await work(item).catch(() => undefined); - if (!stopped) setProgress(from + Math.round((++done / items.length) * (to - from))); - }); + const missedPairs = new Set(); + /** One part of the way there, from one percent to another. A whole percent, so the page only draws again when that changes. What it never could do, it counts by story. */ + const part = async (items: readonly Item[], rowOf: (item: Item) => Comparable, work: (item: Item) => Promise, from: number, to: number) => { + const failed = await workThrough(items, work, { stopped: () => stopped, done: (share) => setProgress(from + Math.round(share * (to - from))) }); + for (const item of failed) missedPairs.add(pairOf(rowOf(item))); }; + const itself = (row: Comparable) => row; + const firstRow = (samples: readonly Sample[]) => samples[0]!.row; void (async () => { setProgress(0); - await part(pairs, diffOf, 0, 50); + await part(pairs, itself, diffOf, 0, 50); const diffOfRow = (row: Comparable) => knownDiffs.peek(pairOf(row)); const sizes = repeatedSizes(pairs.flatMap((row) => diffOfRow(row) ?? [])); - await part(pairs.filter((row) => diffOfRow(row)?.hunks.some((hunk) => sizes.has(sizeKey(hunk)))), hunkKeys, 50, 90); + await part(pairs.filter((row) => diffOfRow(row)?.hunks.some((hunk) => sizes.has(sizeKey(hunk)))), itself, hunkKeys, 50, 90); if (stopped) return; - if (grown?.id !== pairsId) { + const scanned = scansOf(pairs); + if (grown?.id !== scannedId(scanned) || !grown.whole) { // Each straggler joins the first delta of its size it fits, tried against that delta's own pixels, held only for now. - const stragglers = stragglersOf(scansOf(pairs)); + const missedBefore = missedPairs.size; + const stragglers = stragglersOf(scanned); const deltas = [...new Map(stragglers.flatMap(({ deltas }) => deltas.map((delta) => [delta.key, delta] as const))).values()]; const samples = new Map(); - await part(byRow(deltas), async (wanted) => (await cropsIn(wanted)).forEach((crops, at) => samples.set(wanted[at]!.key, crops)), 90, 95); + await part(byRow(deltas), firstRow, async (wanted) => (await cropsIn(wanted)).forEach((crops, at) => samples.set(wanted[at]!.key, crops)), 90, 95); const joins = new Map(); await part( byRow(stragglers), + firstRow, async (wanted) => (await cropsIn(wanted)).forEach(({ golden, current }, at) => { const { key, deltas } = wanted[at]!; @@ -358,22 +402,27 @@ export function useDeltas(batchId: string, rows: readonly RenderRow[] | undefine 100, ); if (stopped) return; - grown = { id: pairsId, joins }; + grown = { id: scannedId(scanned), joins, whole: missedPairs.size === missedBefore }; } setLooked((times) => times + 1); + // By story, since stories that look the same share a pair. + setMissed(pairs.filter((row) => missedPairs.has(pairOf(row))).length); setProgress(null); })(); return () => { stopped = true; }; - }, [looking, pairsId]); + }, [looking, pairsId, tries]); - const joins = useMemo(() => (grown?.id === pairsId ? grown.joins : NO_JOINS), [pairsId, looked]); - const scans = useMemo(() => joinedScans(scansOf(pairs), joins), [pairs, looked, joins]); + const scanned = useMemo(() => scansOf(pairs), [pairs, looked]); + const joins = useMemo(() => (grown?.id === scannedId(scanned) ? grown.joins : NO_JOINS), [scanned]); + const scans = useMemo(() => joinedScans(scanned, joins), [scanned, joins]); const offers = useMemo(() => offeredDeltas(scans, accepted), [scans, accepted]); const taken = useMemo(() => acceptedDeltas(scans, accepted), [scans, accepted]); return { progress, + missed, + retry: () => setTries((times) => times + 1), accepted, offers, taken, diff --git a/ui/src/client/stories/fixtures.ts b/ui/src/client/stories/fixtures.ts index 9dbb991..3b44aef 100644 --- a/ui/src/client/stories/fixtures.ts +++ b/ui/src/client/stories/fixtures.ts @@ -202,7 +202,7 @@ export function deltaFrom(pair: keyof typeof PIXEL_DIFFS, stories: readonly stri /** Nothing found, with actions that are recorded but change nothing. */ export function deltasOf(overrides: Partial = {}): DeltaState { - return { progress: null, accepted: new Set(), offers: [], taken: [], finishes: () => [], accept: fn(), undo: fn(), ...overrides }; + return { progress: null, missed: 0, retry: fn(), accepted: new Set(), offers: [], taken: [], finishes: () => [], accept: fn(), undo: fn(), ...overrides }; } export const failure = (code: string, message: string) => new RequestError(code, message); diff --git a/ui/src/server/hosted.ts b/ui/src/server/hosted.ts index 2bd9177..8fa8bdc 100644 --- a/ui/src/server/hosted.ts +++ b/ui/src/server/hosted.ts @@ -90,7 +90,11 @@ export async function statusOfBatch( export function hostedReviewSource( project: HostedProject, views: BatchViews, - { actor, decided }: { readonly actor: string | null; readonly decided: (comparison: Comparison) => Promise }, + { actor, decided }: { + /** Who's asking, which only what depends on it asks for, since knowing costs the auth adapter a request, and a page asks for hundreds of images at once. */ + readonly actor: () => Promise; + readonly decided: (comparison: Comparison) => Promise; + }, ): ReviewSource { const { batches, storybooks, store, diffs } = project; @@ -104,7 +108,10 @@ export function hostedReviewSource( batch === null ? null : { id: batch.id, gitSha: batch.gitSha, status: await statusOfBatch(project, batch, atCommit ?? (await batches.batchesAt(batch.gitSha, batch.environment))) }; return { - batchView: async (batchId): Promise => views.viewOf(await batches.compareReached(batchId), actor), + async batchView(batchId): Promise { + const [comparison, who] = await Promise.all([batches.compareReached(batchId), actor()]); + return views.viewOf(comparison, who); + }, async batchContext(batchId) { const [batch, open] = await Promise.all([batches.getBatch(batchId), project.pullRequests()]); if (batch === null) throw refusal("unknown-batch", `No batch ${batchId}.`); @@ -119,15 +126,16 @@ export function hostedReviewSource( approvedSince: async (batchId) => views.approvedSinceView(await batches.approvedSinceReached(batchId, project.defaultBranch)), sinceBase: async (batchId) => views.sinceBaseView(await batches.sinceBaseReached(batchId, project.defaultBranch)), async decide(batchId: string, decision: DecisionKind, targets: readonly DecisionTarget[]) { - if (actor === null) throw refusal("not-signed-in", "Sign in to approve or reject."); + const who = await actor(); + if (who === null) throw refusal("not-signed-in", "Sign in to approve or reject."); const before = await batches.compareReached(batchId); const { stale } = exactRows(summarizeBatch(before).inFilter, targets); if (stale > 0) throw refusal("stale-decision", staleDecisionMessage(stale)); const { batch } = before; - await batches.decide({ environment: batch.environment, decision, actor, renders: targets, on: { batchId, gitSha: batch.gitSha } }); + await batches.decide({ environment: batch.environment, decision, actor: who, renders: targets, on: { batchId, gitSha: batch.gitSha } }); const after = await batches.compareReached(batchId); await decided(after); - return views.viewOf(after, actor); + return views.viewOf(after, who); }, async storiesView(): Promise { const batch = (await batches.newestFinished(project.defaultBranch)) ?? (await batches.newestFinished()); diff --git a/ui/src/worker/app.ts b/ui/src/worker/app.ts index e6f2488..2333c0b 100644 --- a/ui/src/worker/app.ts +++ b/ui/src/worker/app.ts @@ -236,7 +236,7 @@ export function createCloudApp(config: CloudConfig): Hono { createReviewApi(async (context) => { const found = await readyProject(context); return hostedReviewSource(found.hosted, found.views, { - actor: await login.writerOf(context.req.raw), + actor: () => login.writerOf(context.req.raw), decided: (comparison) => afterResponse(context, publishDecided(found, comparison)), }); }), diff --git a/ui/test/delta-scan.test.ts b/ui/test/delta-scan.test.ts new file mode 100644 index 0000000..ebc3dd9 --- /dev/null +++ b/ui/test/delta-scan.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, test } from "vitest"; +import { RequestError } from "../src/client/api.ts"; +import { workThrough } from "../src/client/deltas.ts"; + +const answered = (status: number) => new RequestError("bad-response", `The server answered ${status}.`, null, status); +const noWait = async () => undefined; + +/** Work that fails each item with what `failures` lists for it, one per try, and then passes. */ +function failing(failures: Record) { + const tries: string[] = []; + const work = async (item: string) => { + const at = tries.filter((tried) => tried === item).length; + tries.push(item); + const failure = failures[item]?.[at]; + if (failure !== undefined) throw failure; + }; + return { tries, work }; +} + +describe("workThrough", () => { + test("tries again whatever a busy or broken server or a dropped connection refused, and passes it once it works", async () => { + const { tries, work } = failing({ busy: [answered(429)], broken: [answered(500), answered(503)], dropped: [new RequestError("unreachable", "Can't reach Selfie.")] }); + const waits: number[] = []; + const failed = await workThrough(["busy", "broken", "dropped", "fine"], work, { wait: async (ms) => void waits.push(ms) }); + expect(failed).toEqual([]); + expect(tries.filter((item) => item === "broken")).toHaveLength(3); + expect(waits.sort((a, b) => a - b)).toEqual([500, 500, 500, 2_000]); + }); + + test("gives back what never worked, after a few tries, and what can't work later, at once", async () => { + const { tries, work } = failing({ busy: Array(5).fill(answered(429)), missing: [answered(404)], undecodable: [new Error("The source image cannot be decoded.")] }); + const failed = await workThrough(["busy", "missing", "fine", "undecodable"], work, { wait: noWait }); + expect([...failed].sort()).toEqual(["busy", "missing", "undecodable"]); + expect(tries.filter((item) => item === "busy")).toHaveLength(3); + expect(tries.filter((item) => item === "missing")).toHaveLength(1); + }); + + test("says how far through it is, counting what failed", async () => { + const shares: number[] = []; + const { work } = failing({ missing: [answered(404)] }); + await workThrough(["missing", "b", "c", "d"], work, { done: (share) => shares.push(share), wait: noWait }); + expect(shares.sort()).toEqual([0.25, 0.5, 0.75, 1]); + }); + + test("starts nothing once stopped, and says nothing more, nor gives back what it didn't try", async () => { + const shares: number[] = []; + const tried: string[] = []; + let stopped = false; + const failed = await workThrough( + ["a", "b", "c", "d", "e", "f"], + async (item) => { + tried.push(item); + stopped = true; + }, + { stopped: () => stopped, done: (share) => shares.push(share), wait: noWait }, + ); + expect(tried).toEqual(["a"]); + expect(failed).toEqual([]); + expect(shares).toEqual([]); + }); +}); diff --git a/ui/test/workerd/cloud.workerd.test.ts b/ui/test/workerd/cloud.workerd.test.ts index 914df74..619c99f 100644 --- a/ui/test/workerd/cloud.workerd.test.ts +++ b/ui/test/workerd/cloud.workerd.test.ts @@ -23,6 +23,8 @@ const NEXT = "22222222-2222-4222-8222-222222222222"; const fromBase64 = (text: string) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0)); const png = fromBase64("iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4XmM4IScHRwzEcQCxYxBBF7FZ1QAAAABJRU5ErkJggg=="); const hash = "6fc35503986a1b85896ca807408798a0bbbf1ad557fd91ee6d19f5ba0469e636"; +/** The golden of the one diff kept here, against `hash`. */ +const KEPT_DIFF = "9".repeat(64); const statuses: { sha: string; status: CommitStatus; url: string }[] = []; /** What GitHub says is open, or why it won't say. */ @@ -409,18 +411,27 @@ describe("the cloud service", () => { }); it("keeps a diff a client worked out, for showing", async () => { - const other = "9".repeat(64); const stats = { hunks: [], changedPixels: 1 }; - expect((await api("PUT", `/diffs/${hash}/${other}/image`, null, png)).status).toBe(403); - expect((await api("PUT", `/diffs/${hash}/${other}`, null, stats)).status).toBe(403); - expect((await api("PUT", `/diffs/${hash}/${other}/image`, UPLOAD, png)).status).toBe(200); - expect((await api("PUT", `/diffs/${hash}/${other}`, UPLOAD, stats)).status).toBe(200); - expect(await (await review("GET", `/diffs/${hash}/${other}`)).json()).toEqual(stats); - expect(await (await review("GET", `/diffs/${hash}/${other}/image`)).status).toBe(200); + expect((await api("PUT", `/diffs/${hash}/${KEPT_DIFF}/image`, null, png)).status).toBe(403); + expect((await api("PUT", `/diffs/${hash}/${KEPT_DIFF}`, null, stats)).status).toBe(403); + expect((await api("PUT", `/diffs/${hash}/${KEPT_DIFF}/image`, UPLOAD, png)).status).toBe(200); + expect((await api("PUT", `/diffs/${hash}/${KEPT_DIFF}`, UPLOAD, stats)).status).toBe(200); + expect(await (await review("GET", `/diffs/${hash}/${KEPT_DIFF}`)).json()).toEqual(stats); + expect(await (await review("GET", `/diffs/${hash}/${KEPT_DIFF}/image`)).status).toBe(200); expect((await review("POST", "/notes", { signedIn: true, body: { story: "a", batchId: FIRST, imageHash: hash, box: null, text: "hi" } })).status).toBe(403); expect((await review("POST", "/renders", { signedIn: true, body: { stories: ["a"] } })).status).toBe(403); }); + it("never asks the auth adapter who's looking at an image or a diff, since a page asks for hundreds at once", async () => { + // A session the adapter can't answer for fails any route that does ask. + const broken = { origin: ORIGIN, cookie: "__Host-pgstencil.session_token=broken" }; + const get = (route: string) => app.request(`${ORIGIN}/diffplug/selfie/api${route}`, { headers: broken }); + const logged = vi.spyOn(console, "error").mockImplementation(() => undefined); + expect((await get(`/batches/${FIRST}`)).status).toBe(500); + logged.mockRestore(); + for (const route of [`/images/${hash}`, `/diffs/${hash}/${KEPT_DIFF}`, `/diffs/${hash}/${KEPT_DIFF}/image`]) expect((await get(route)).status, route).toBe(200); + }); + it("keeps a record a client worked out, unread, and hands anyone a batch's worth in one answer", async () => { const pairs = Array.from({ length: 20 }, (_, i) => ({ current: hash, golden: i.toString(16).padStart(64, "0") })); const text = (i: number) => `{"not":"read here","i":${i}}`;