Public: anyone can read this; the crew can change it.

Thumbs are taken at the card's real size after the first paint, and retaken when a week old #16791

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16258-thumbs-are-taken-at-the-card-s-real-size → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/16258-thumbs-are-taken-at-the-card-s-real-size was merged into main as a9f396b.

Review

Sign in to review this change.
6 files changed +223 −12
scripts/unused-exports-allow.json +1
@@ -10,6 +10,7 @@
1010 "src/apps/migration_mode.ts migrationOrigin",
1111 "src/apps/relay_wait.ts clearRelayWaits",
1212 "src/apps/toolbar.ts TOOLBAR_PATH",
13 "src/looks/capture.ts FIRST_PAINT_EXPRESSION",
1314 "src/billing/sync.ts setStripeFetch",
1415 "src/boards/live_hub.ts hubsOpen",
1516 "src/boards/model_fill.ts useModel",
src/core/looks.ts +16
@@ -42,6 +42,22 @@ export const LOOK_WINDOWS: Readonly<
4242 thumb: LOOK_SIZES.desktop,
4343 };
4444
45 /**
46 * The device pixel ratio each picture is taken at: a phone is held at twice
47 * its CSS pixels, so its pictures are too. A thumb is the desktop window,
48 * reduced to 640×400. Its card is fluid (the door shelf, `.door-shelf` in
49 * style/content.ts: two columns under 720px, four above, 16:9, so about 170
50 * to 330 CSS px wide), and 640 is twice the widest of those: the picture is
51 * already at 2x for its card, which a window of the card's own size could not
52 * give (headless Chromium keeps a minimum width), so the scale stays 1.
53 */
54 export const LOOK_SCALES: Readonly<Record<LookKind, number>> = {
55 phone: 2,
56 narrow: 2,
57 desktop: 1,
58 thumb: 1,
59 };
60
4561 /**
4662 * The width of a thumb taken in a 200×125 window, before thumbs were the
4763 * desktop page reduced: a corner of the page, cropped, taken as the owner.
src/looks/capture.ts +41 −1
@@ -61,6 +61,8 @@ export interface LookInput {
6161 readonly out: string;
6262 readonly width: number;
6363 readonly height: number;
64 /** The device pixel ratio the picture is taken at; 1 when unset. */
65 readonly scale?: number | undefined;
6466 /** Force the page's `prefers-color-scheme` to dark; light (the browser's own) when unset. */
6567 readonly dark?: boolean | undefined;
6668 /** A browser that has no picture by then is killed; the look fails. */
@@ -186,6 +188,43 @@ const MAX_ENTRIES = 500;
186188 /** How long after load the page gets to settle (the last paint, the last shift). */
187189 const SETTLE_MS = 400;
188190
191 /** The most a picture waits for a page's first paint after its load. */
192 const PAINT_MS = 3_000;
193
194 /**
195 * Settles after the first contentful paint, and then two frames more; at once on a browser without
196 * paint timing.
197 */
198 const FIRST_PAINT = `new Promise((done) => {
199 const frames = () => requestAnimationFrame(() => requestAnimationFrame(() => done(true)));
200 const seen = () => performance.getEntriesByName("first-contentful-paint").length > 0;
201 if (seen()) return frames();
202 try {
203 const watch = new PerformanceObserver(() => { if (seen()) { watch.disconnect(); frames(); } });
204 watch.observe({ type: "paint", buffered: true });
205 } catch (_) { done(false); }
206 })`;
207
208 /**
209 * A page that draws late (a game, a canvas) is waited for, bounded: the picture is taken after its
210 * first paint, never before it. The expression is evaluated with `awaitPromise`; a timeout or an
211 * error is not a failure, the picture is taken as the page stands.
212 */
213 export async function awaitFirstPaint(
214 send: (method: string, params: Record<string, unknown>) => Promise<unknown>,
215 deadline: number,
216 paintMs: number = PAINT_MS,
217 ): Promise<void> {
218 await within(
219 send("Runtime.evaluate", { expression: FIRST_PAINT, awaitPromise: true, returnByValue: true }),
220 Math.min(deadline, Date.now() + paintMs),
221 "paint",
222 ).catch(() => undefined);
223 }
224
225 /** Exported for the test that runs it: the expression that settles after the first paint. */
226 export const FIRST_PAINT_EXPRESSION = FIRST_PAINT;
227
189228 /** Runs before any page script: collects the entries the summary grades. */
190229 const OBSERVER = `(() => {
191230 if (window.top !== window) return;
@@ -611,7 +650,7 @@ async function shoot(
611650 {
612651 width: input.width,
613652 height: input.height,
614 deviceScaleFactor: 1,
653 deviceScaleFactor: input.scale ?? 1,
615654 mobile: false,
616655 },
617656 sessionId,
@@ -633,6 +672,7 @@ async function shoot(
633672 // A page that never finishes loading is pictured as it stands.
634673 await Promise.race([loaded, Bun.sleep(LOAD_MS)]);
635674 await Bun.sleep(SETTLE_MS);
675 await awaitFirstPaint((method, params) => dt.send(method, params, sessionId), deadline);
636676 const where = await dt.send(
637677 "Runtime.evaluate",
638678 { expression: "location.href", returnByValue: true },
src/looks/service.ts +34 −10
@@ -58,8 +58,10 @@ import {
5858 LOOK_THEMES,
5959 type LookTheme,
6060 LOOK_SIZES,
61 LOOK_SCALES,
6162 LOOK_WINDOWS,
6263 lookSlot,
64 getLook,
6365 looksForEnv,
6466 recordLook,
6567 type Look,
@@ -80,7 +82,7 @@ import { blobKey, deleteLooksAndObjects, deleteObjects } from "./archive.ts";
8082 import { keepAsMain } from "./main_looks.ts";
8183 import { closeBrowsers, findChromium, isNoBrowser, lookLanes, takeLook, type Capture } from "./capture.ts";
8284 import { browserRefusal } from "./chromium.ts";
83 import { backoff, type BackoffClock } from "./backoff.ts";
85 import { backoff, realClock, type BackoffClock } from "./backoff.ts";
8486 import { reduceToThumb } from "./thumb.ts";
8587 import { during } from "../perf/jobs.ts";
8688
@@ -228,6 +230,9 @@ const GRANT_TTL_MS = 60_000;
228230 */
229231 export const LOOK_BACKOFF_MS: readonly number[] = [30_000, 120_000, 600_000];
230232
233 /** A thumb on a running production this old is retaken by the sweep. */
234 export const THUMB_STALE_MS = 7 * 24 * 3_600_000;
235
231236 export const looksRoot = (dataDir: string): string => join(dataDir, "looks");
232237
233238 /** Where a picture is written while it is being taken. */
@@ -251,9 +256,11 @@ export const lookPath = (
251256 * thumb from before thumbs were the page reduced (`LEGACY_THUMB_WIDTH`):
252257 * that one is retaken, and shown until it is.
253258 */
254 export function keepLook(dataDir: string, look: Look): boolean {
259 export function keepLook(dataDir: string, look: Look, staleBefore?: number): boolean {
255260 if (look.error !== null) return false;
256261 if (look.kind !== "thumb") return true;
262 // A thumb older than the cut is one to retake; it is still shown until the retake lands.
263 if (staleBefore !== undefined && Date.parse(look.createdAt) < staleBefore) return false;
257264 let fd: number | undefined;
258265 try {
259266 fd = openSync(join(dataDir, look.path), "r");
@@ -318,10 +325,23 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
318325 const envKey = (q: { appId: string; env: EnvName }): string => `${q.appId}/${q.env}`;
319326 let stopped = false;
320327 /** Failed looks by app, environment and head: each waits out its backoff (#11509). */
321 const failures = backoff(LOOK_BACKOFF_MS, options.clock);
328 const clock = options.clock ?? realClock;
329 const failures = backoff(LOOK_BACKOFF_MS, clock);
322330 const failKey = (q: { appId: string; env: EnvName; commitOid: string }): string =>
323331 `${q.appId}/${q.env}/${q.commitOid}`;
324332
333 /**
334 * A picture that could not be taken is a row saying why, unless a picture
335 * is already kept in that slot: a failed retake leaves the old one (#16258).
336 * Any kept picture counts, an attached one too: a failure never replaces a
337 * person's attachment with an error row.
338 */
339 function recordFailure(input: Parameters<typeof recordLook>[1]): void {
340 const old = getLook(app.db, input.appId, input.env, input.commitOid, input.page ?? DEFAULT_PAGE, input.kind, input.theme);
341 if (old !== undefined && old.error === null && old.path !== "") return;

Non-blocking: any kept picture, an attached one included, now survives a failed retake. Add a test with an attached look so this behaviour change is pinned.

342 recordLook(app.db, input);
343 }
344
325345 /** A look failed: try again after the next backoff, or give up with one line. */
326346 function failed(item: Pending): void {
327347 const verdict = failures.failed(failKey(item), () => {
@@ -504,7 +524,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
504524 const last = item.again === true;
505525 const error = last ? notAgain(reason) : reason;
506526 for (const { page, kind, theme } of missing(item.appId, item.env, item.commitOid, pagesOf(item, declared)))
507 recordLook(app.db, {
527 recordFailure({
508528 appId: item.appId,
509529 env: item.env,
510530 commitOid: item.commitOid,
@@ -567,6 +587,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
567587 item.commitOid,
568588 pages,
569589 item.swept === true,
590 item.swept === true && item.env === "production",
570591 );
571592 if (wanted.length === 0) return;
572593 // An app still warming up gets no browser: wait, bounded, until it
@@ -576,7 +597,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
576597 if (stopped) return;
577598 log.warn("no picture: the app is not serving", { app: record.slug, env: item.env, why: heard });
578599 for (const { page, kind, theme } of wanted)
579 recordLook(app.db, {
600 recordFailure({
580601 appId: item.appId,
581602 env: item.env,
582603 commitOid: item.commitOid,
@@ -638,7 +659,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
638659 for (const [index, { page, kind, theme }] of wanted.entries()) {
639660 if (stopped) return;
640661 if (verdict !== undefined) {
641 recordLook(app.db, {
662 recordFailure({
642663 appId: item.appId,
643664 env: item.env,
644665 commitOid: item.commitOid,
@@ -673,6 +694,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
673694 url,
674695 out: staged,
675696 ...LOOK_WINDOWS[kind],
697 scale: LOOK_SCALES[kind],
676698 ...(theme === "dark" ? { dark: true } : {}),
677699 timeoutMs: CAPTURE_TIMEOUT_MS,
678700 // One browser for the whole look: it is kept while pictures follow.
@@ -739,7 +761,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
739761 theme,
740762 error: taken.error,
741763 });
742 recordLook(app.db, { ...row, kind, path: "", error: taken.error });
764 recordFailure({ ...row, kind, path: "", error: taken.error });
743765 // One failure is the verdict for this try: the other pictures
744766 // would meet the same page, so they are filed with its reason
745767 // and no browser is opened for them.
@@ -775,13 +797,15 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
775797 commitOid: string,
776798 pages: readonly string[] | undefined,
777799 failedCounts = false,
800 retakeStale = false,
778801 ): { page: string; kind: LookKind; theme: LookTheme }[] {
802 const staleBefore = retakeStale ? clock.now() - THUMB_STALE_MS : undefined;
779803 const have = new Set(
780804 looksForEnv(app.db, appId, env, "any")
781805 .filter(
782806 (l) =>
783807 l.commitOid === commitOid &&
784 (keepLook(dataDir, l) || (failedCounts && l.error !== null)),
808 (keepLook(dataDir, l, staleBefore) || (failedCounts && l.error !== null)),
785809 )
786810 .map((l) => lookSlot(l.page, l.kind, l.theme)),
787811 );
@@ -826,7 +850,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
826850 pinned.has(record.repoId) &&
827851 record.access === "public" &&
828852 getRepoById(app.db, record.repoId)?.visibility === "public" &&
829 missing(record.id, "production", status.commitOid, status.looks, true)
853 missing(record.id, "production", status.commitOid, status.looks, true, true)
830854 .length > 0
831855 )
832856 toWake.push(record);
@@ -834,7 +858,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
834858 // A picture that failed at this head had its turn: the next
835859 // deploy tries again, not every sweep.
836860 const { commitOid, looks: pages } = status;
837 if (missing(record.id, "production", commitOid, pages, true).length > 0)
861 if (missing(record.id, "production", commitOid, pages, true, true).length > 0)
838862 enqueue({
839863 appId: record.id,
840864 env: "production",
test/look-first-paint.test.ts added +66
@@ -0,0 +1,66 @@
1 import { expect, test } from "bun:test";
2 import { awaitFirstPaint, FIRST_PAINT_EXPRESSION } from "../src/looks/capture.ts";
3
4 test("the picture waits for the paint: the expression is evaluated with awaitPromise", async () => {
5 const calls: { method: string; params: Record<string, unknown> }[] = [];
6 let settled = false;
7 const send = async (method: string, params: Record<string, unknown>) => {
8 calls.push({ method, params });
9 await new Promise<void>((r) => queueMicrotask(r));
10 settled = true;
11 return {};
12 };
13 await awaitFirstPaint(send, Date.now() + 5_000);
14 expect(settled).toBe(true);
15 expect(calls).toHaveLength(1);
16 expect(calls[0]?.method).toBe("Runtime.evaluate");
17 expect(calls[0]?.params["awaitPromise"]).toBe(true);
18 expect(calls[0]?.params["expression"]).toBe(FIRST_PAINT_EXPRESSION);
19 });
20
21 test("a page that never paints is waited for only so long, then pictured anyway", async () => {
22 const started = Date.now();
23 await awaitFirstPaint(() => new Promise(() => {}), Date.now() + 5_000, 80);
24 expect(Date.now() - started).toBeLessThan(1_000);
25 });
26
27 test("the overall deadline caps the wait", async () => {
28 const started = Date.now();
29 await awaitFirstPaint(() => new Promise(() => {}), Date.now() + 50, 5_000);
30 expect(Date.now() - started).toBeLessThan(1_000);
31 });
32
33 test("an error from the page does not fail the picture", async () => {
34 await expect(awaitFirstPaint(() => Promise.reject(new Error("detached")), Date.now() + 1_000)).resolves.toBeUndefined();
35 });
36
37 test("the expression resolves only after a first contentful paint and two frames", async () => {
38 const g = globalThis as Record<string, unknown>;
39 const saved = { performance: g["performance"], PerformanceObserver: g["PerformanceObserver"], raf: g["requestAnimationFrame"] };
40 let painted = false;
41 let notify: () => void = () => {};
42 g["performance"] = { getEntriesByName: () => (painted ? [{}] : []) };
43 g["PerformanceObserver"] = class {
44 constructor(cb: () => void) { notify = cb; }
45 observe() {}
46 disconnect() {}
47 };
48 let frames = 0;
49 g["requestAnimationFrame"] = (f: () => void) => { frames++; queueMicrotask(f); };
50 try {
51 let done = false;
52 const run = (0, eval)(FIRST_PAINT_EXPRESSION) as Promise<boolean>;
53 run.then(() => { done = true; });
54 await new Promise<void>((r) => queueMicrotask(r));
55 expect(done).toBe(false);
56 expect(frames).toBe(0);
57 painted = true;
58 notify();
59 expect(await run).toBe(true);
60 expect(frames).toBe(2);
61 } finally {
62 g["performance"] = saved.performance;
63 g["PerformanceObserver"] = saved.PerformanceObserver;
64 g["requestAnimationFrame"] = saved.raf;
65 }
66 });
test/looks.test.ts +65 −1
@@ -117,8 +117,10 @@ describe("the look", () => {
117117 // The backoff's clock: real time, but a retry runs only when a test
118118 // fires it, so a wait of minutes is a line of the test (#11509).
119119 const scheduled: { ms: number; fn: () => void }[] = [];
120 /** How far ahead of the real time the looks' clock is told it is. */
121 let skew = 0;
120122 const clock: BackoffClock = {
121 now: () => Date.now(),
123 now: () => Date.now() + skew,
122124 after(ms, fn) {
123125 const entry = { ms, fn };
124126 scheduled.push(entry);
@@ -1273,6 +1275,68 @@ describe("the look", () => {
12731275 expect(callsAt("production")).toHaveLength(before + 1);
12741276 });
12751277
1278 test("the sweep retakes a thumb a week old on a running production, and a failed retake keeps the old picture (#16258)", async () => {
1279 const DAY = 24 * 3_600_000;
1280 const head = runtime.envStatus(record, "production")!.commitOid;
1281 // The test before left this head's thumb failed; picture it again.
1282 const thumbPath = `looks/${record.id}/production/${head}-thumb.png`;
1283 writeFileSync(join(dataDir, thumbPath), PNG);
1284 recordLook(app.db, { appId: record.id, env: "production", commitOid: head, kind: "thumb", path: thumbPath });
1285 const thumbAt = (): Look =>
1286 looksForEnv(app.db, record.id, "production").find(
1287 (l) => l.kind === "thumb" && l.commitOid === head && l.page === "/",
1288 )!;
1289 expect(thumbAt().error).toBeNull();
1290 const thumbCalls = () => callsAt("production").filter((c) => c.out.endsWith("-thumb.png")).length;
1291 const before = thumbCalls();
1292 try {
1293 // Six days on: still fresh, nothing is taken.
1294 skew = 6 * DAY;
1295 looks.sweep();
1296 await looks.idle();
1297 expect(thumbCalls()).toBe(before);
1298
1299 // Eight days on: the thumb alone is taken again, and replaced.
1300 skew = 8 * DAY;
1301 const old = readFileSync(join(dataDir, thumbAt().path));
1302 looks.sweep();
1303 await looks.idle();
1304 expect(thumbCalls()).toBe(before + 1);
1305 expect(callsAt("production").at(-1)!.out.endsWith("-thumb.png")).toBe(true);
1306 expect(callsAt("production").at(-1)!.scale).toBe(1);
1307 expect(thumbAt().error).toBeNull();
1308 expect(readFileSync(join(dataDir, thumbAt().path)).equals(old)).toBe(false);
1309
1310 // The clock still reads a week on from that retake: it is stale again,
1311 // the browser falls over, and the picture on record stays.
1312 skew = 16 * DAY;
1313 const kept = readFileSync(join(dataDir, thumbAt().path));
1314 modes.set(helloHost("production"), "fail");
1315 looks.sweep();
1316 await looks.idle();
1317 expect(thumbCalls()).toBe(before + 2);
1318 expect(thumbAt().error).toBeNull();
1319 expect(readFileSync(join(dataDir, thumbAt().path)).equals(kept)).toBe(true);
1320 // And it waits out its backoff rather than trying every sweep.
1321 looks.sweep();
1322 await looks.idle();
1323 expect(thumbCalls()).toBe(before + 2);
1324 } finally {
1325 skew = 0;
1326 modes.delete(helloHost("production"));
1327 for (const entry of [...scheduled]) fire(entry);
1328 await looks.idle();
1329 }
1330 });
1331
1332 test("phones are pictured at twice their pixels; the desktop and the thumb at one", async () => {
1333 const seen = callsAt("production");
1334 const scaleOf = (suffix: string) => seen.find((c) => c.out.endsWith(suffix))?.scale;
1335 expect(scaleOf("-phone.png")).toBe(2);
1336 expect(scaleOf("-desktop.png")).toBe(1);
1337 expect(scaleOf("-thumb.png")).toBe(1);
1338 });
1339
12761340 test("pictures are shown only to those allowed to see them (#727): on a public repository hosting a private app, a stranger gets none, a signed-in reader the thumb, a writer all", async () => {
12771341 // `hello` is a private app; its repository is made public here.
12781342 expect(record.access).toBe("private");

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs