Public: anyone can read this; the crew can change it.
Looks that work well: a failed picture is retried, a sleeping app says so, a card says why it has no picture, and the thumbs are the ones the owner would choose #1449
scout/forge:scout/1150-looks-that-work-well-a-failed-picture-is → main 6 commits fork
13 files
changed +705
−48
docs/APPS.md +16 −1
| @@ -739,7 +739,9 @@ The phone and desktop pictures are what the repository's owner would see: | ||
| 739 | 739 | headless Chromium is pointed at the forge's own listener with the app's |
| 740 | 740 | hostname resolved to loopback, through the grant door, so the app renders for |
| 741 | 741 | a signed-in admin exactly as when the owner opens it — and they are its |
| 742 | writers' alone. The thumb is taken as nobody, for the tiles strangers see. A | |
| 742 | writers' alone. The thumb of a public app is taken as nobody, for the tiles | |
| 743 | strangers see; a thumb of an app that is not public is the owner's, since a | |
| 744 | stranger would only be sent to the forge's sign-in. A | |
| 743 | 745 | public app on a public repository is the world's to see, so all three of its |
| 744 | 746 | pictures are taken as nobody, and a reader of its pulls sees the Look card |
| 745 | 747 | too; each row records who it was `taken_as` (#727, #738). It is taken as the page loads — what an |
| @@ -764,6 +766,19 @@ It stays when the head moves on and goes with the preview when the pull | ||
| 764 | 766 | closes. |
| 765 | 767 | |
| 766 | 768 | |
| 769 | Before the browser goes, the forge walks the same road over its own | |
| 770 | listener (`looks/preflight.ts`): a hop that leaves the forge (a public name | |
| 771 | this pod resolves differently from the world), a 404 ("not serving"), the | |
| 772 | forge's sign-in or a browser's error page is a failed look with that | |
| 773 | reason, never a picture; the browser itself resolves nothing but the app's | |
| 774 | host. A failed picture is tried again after 5 minutes, then 10, 20, … up | |
| 775 | to a day (`look.attempts`), whenever the sweep finds the machine quiet. A | |
| 776 | first paint that is one flat colour is waited on and taken again. A thumb | |
| 777 | of a running production older than a week is retaken (the old one stays up | |
| 778 | if the retake fails), and when an app's access changes every picture taken | |
| 779 | as someone it no longer treats that way is retaken. A card with no picture | |
| 780 | says why in one line (`lookReason`) or sets the app's name on a calm ground. | |
| 781 | ||
| 767 | 782 | ## The crew |
| 768 | 783 | |
| 769 | 784 | An agent is created once (`New agent`: a name, a model, a brief) and given |
src/actions/attach_look.ts +1
| @@ -139,6 +139,7 @@ export function attachLook( | ||
| 139 | 139 | createdAt: new Date().toISOString(), |
| 140 | 140 | error: null, |
| 141 | 141 | takenAs: "owner", |
| 142 | attempts: 0, | |
| 142 | 143 | attachedBy: actor.username, |
| 143 | 144 | note: note.value, |
| 144 | 145 | }); |
src/actions/front.ts +22
| @@ -37,6 +37,7 @@ import { | ||
| 37 | 37 | import { getIssuesByIds } from "../core/issues.ts"; |
| 38 | 38 | import { |
| 39 | 39 | DEFAULT_PAGE, |
| 40 | lookReason, | |
| 40 | 41 | looksForApps, |
| 41 | 42 | lookUrl, |
| 42 | 43 | type Look, |
| @@ -69,6 +70,8 @@ export interface FrontEntry { | ||
| 69 | 70 | readonly state: EnvState | undefined; |
| 70 | 71 | /** The thumb of production's home page, as a stranger sees it. */ |
| 71 | 72 | readonly picture: string | undefined; |
| 73 | /** Why there is no picture, in a line a stranger may read; undefined when there is nothing to say. */ | |
| 74 | readonly reason: string | undefined; | |
| 72 | 75 | readonly pinned: boolean; |
| 73 | 76 | readonly signals: FrontSignals; |
| 74 | 77 | readonly score: number; |
| @@ -217,6 +220,15 @@ export function frontPage(app: App, now = Date.now()): FrontPage { | ||
| 217 | 220 | l.kind === "thumb" && |
| 218 | 221 | thumbs.check(l), |
| 219 | 222 | ); |
| 223 | const homeThumb = looks.find( | |
| 224 | (l) => | |
| 225 | record !== undefined && | |
| 226 | l.appId === record.id && | |
| 227 | l.env === "production" && | |
| 228 | l.commitOid === production?.commitOid && | |
| 229 | l.page === DEFAULT_PAGE && | |
| 230 | l.kind === "thumb", | |
| 231 | ); | |
| 220 | 232 | const scored = scores.get(repo.id) ?? { |
| 221 | 233 | s: { awakeHours: 0, ships: 0, forks: 0, shippedAt: null }, |
| 222 | 234 | score: 0, |
| @@ -234,6 +246,15 @@ export function frontPage(app: App, now = Date.now()): FrontPage { | ||
| 234 | 246 | thumb === undefined |
| 235 | 247 | ? undefined |
| 236 | 248 | : lookUrl(`/${repo.ownerName}/${repo.name}`, thumb), |
| 249 | reason: | |
| 250 | thumb !== undefined || record === undefined | |
| 251 | ? undefined | |
| 252 | : lookReason({ | |
| 253 | state: open ? production?.state : undefined, | |
| 254 | thumb: homeThumb, | |
| 255 | writersOnly: !open, | |
| 256 | now, | |
| 257 | }), | |
| 237 | 258 | pinned: isPinned, |
| 238 | 259 | signals, |
| 239 | 260 | score: open ? scored.score : frontScore(signals, now, frontWeights(db)), |
| @@ -462,6 +483,7 @@ export function frontJson( | ||
| 462 | 483 | url: `/${e.repo.ownerName}/${e.repo.name}`, |
| 463 | 484 | state: e.state ?? null, |
| 464 | 485 | picture: e.picture ?? null, |
| 486 | reason: e.reason ?? null, | |
| 465 | 487 | pinned: e.pinned, |
| 466 | 488 | score: Math.round(e.score * 100) / 100, |
| 467 | 489 | signals: e.signals, |
src/core/looks.ts +60 −2
| @@ -86,6 +86,8 @@ export interface Look { | ||
| 86 | 86 | readonly error: string | null; |
| 87 | 87 | /** Who the picture was taken as: the owner (an admin), or nobody. */ |
| 88 | 88 | readonly takenAs: "owner" | "nobody"; |
| 89 | /** Failures in a row at this head; 0 for a picture. */ | |
| 90 | readonly attempts: number; | |
| 89 | 91 | /** The person who attached it, for a look the forge did not take. */ |
| 90 | 92 | readonly attachedBy: string | null; |
| 91 | 93 | /** The one line that says what an attached look shows. */ |
| @@ -103,6 +105,7 @@ interface Row { | ||
| 103 | 105 | created_at: string; |
| 104 | 106 | error: string | null; |
| 105 | 107 | taken_as: "owner" | "nobody"; |
| 108 | attempts: number; | |
| 106 | 109 | attached_by: string | null; |
| 107 | 110 | note: string | null; |
| 108 | 111 | } |
| @@ -118,6 +121,7 @@ const toLook = (r: Row): Look => ({ | ||
| 118 | 121 | createdAt: r.created_at, |
| 119 | 122 | error: r.error, |
| 120 | 123 | takenAs: r.taken_as, |
| 124 | attempts: r.attempts, | |
| 121 | 125 | attachedBy: r.attached_by, |
| 122 | 126 | note: r.note, |
| 123 | 127 | }); |
| @@ -141,10 +145,11 @@ export interface RecordLookInput { | ||
| 141 | 145 | export function recordLook(db: Database, input: RecordLookInput): Look { |
| 142 | 146 | const page = input.page ?? DEFAULT_PAGE; |
| 143 | 147 | db.query( |
| 144 | `INSERT INTO look (id, app_id, env, commit_oid, page, kind, path, error, taken_as, attached_by, note) | |
| 145 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) | |
| 148 | `INSERT INTO look (id, app_id, env, commit_oid, page, kind, path, error, taken_as, attached_by, note, attempts) | |
| 149 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, CASE WHEN ?8 IS NULL THEN 0 ELSE 1 END) | |
| 146 | 150 | ON CONFLICT (app_id, env, commit_oid, page, kind) DO UPDATE SET |
| 147 | 151 | path = excluded.path, error = excluded.error, taken_as = excluded.taken_as, |
| 152 | attempts = CASE WHEN excluded.error IS NULL THEN 0 ELSE look.attempts + 1 END, | |
| 148 | 153 | created_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`, |
| 149 | 154 | ).run( |
| 150 | 155 | newId(), |
| @@ -252,6 +257,59 @@ export const lookVersion = (look: Look): string => | ||
| 252 | 257 | export const lookUrl = (base: string, look: Look): string => |
| 253 | 258 | `${base}/looks/${look.env}/${look.commitOid}/${lookSlot(look.page, look.kind)}.png?v=${lookVersion(look)}`; |
| 254 | 259 | |
| 260 | /** The first wait after a failed picture; each failure doubles it. */ | |
| 261 | export const RETRY_FIRST_MS = 5 * 60_000; | |
| 262 | /** No wait is longer than a day. */ | |
| 263 | export const RETRY_MAX_MS = 24 * 3_600_000; | |
| 264 | /** A thumb on a running production is retaken when older than this. */ | |
| 265 | export const STALE_THUMB_MS = 7 * 24 * 3_600_000; | |
| 266 | ||
| 267 | /** When a failed picture may be tried again, in epoch ms; undefined for a picture. */ | |
| 268 | export function retryAt(look: Look): number | undefined { | |
| 269 | if (look.error === null) return undefined; | |
| 270 | const wait = Math.min( | |
| 271 | RETRY_MAX_MS, | |
| 272 | RETRY_FIRST_MS * 2 ** Math.max(0, Math.min(look.attempts, 30) - 1), | |
| 273 | ); | |
| 274 | return Date.parse(look.createdAt) + wait; | |
| 275 | } | |
| 276 | ||
| 277 | /** Whether a thumb is old enough to be retaken while its app is up. */ | |
| 278 | export const staleThumb = (look: Look, now: number): boolean => | |
| 279 | look.kind === "thumb" && | |
| 280 | look.error === null && | |
| 281 | now - Date.parse(look.createdAt) > STALE_THUMB_MS; | |
| 282 | ||
| 283 | const clock = (at: number): string => | |
| 284 | `${new Date(at).toISOString().slice(11, 16)} UTC`; | |
| 285 | ||
| 286 | /** | |
| 287 | * The one line the forge has for an app card with no picture, or undefined | |
| 288 | * when there is nothing to say (the card then sets the app's name on a | |
| 289 | * calm ground). Never the browser's own words: a stranger reads this. | |
| 290 | */ | |
| 291 | export function lookReason(input: { | |
| 292 | /** The environment's state, when the viewer may be told it. */ | |
| 293 | readonly state: string | undefined; | |
| 294 | /** The home page's thumb row at production's head, when there is one. */ | |
| 295 | readonly thumb: Look | undefined; | |
| 296 | /** Whether the pictures of this app are the writers' alone. */ | |
| 297 | readonly writersOnly: boolean; | |
| 298 | readonly now: number; | |
| 299 | }): string | undefined { | |
| 300 | if (input.writersOnly) return "pictures are the writers' on this private app"; | |
| 301 | const { state, thumb } = input; | |
| 302 | if (state === undefined) return undefined; | |
| 303 | if (state === "deploying") return "taking a picture once it is up"; | |
| 304 | if (state !== "running" && state !== "asleep") return "not serving"; | |
| 305 | if (thumb?.error != null) { | |
| 306 | const at = retryAt(thumb); | |
| 307 | return at === undefined || at <= input.now | |
| 308 | ? "failed; retrying soon" | |
| 309 | : `failed; retrying at ${clock(at)}`; | |
| 310 | } | |
| 311 | return "taking a picture"; | |
| 312 | } | |
| 255 | 313 | /** Whether a look was attached by a person, not taken by the forge. */ |
| 256 | 314 | export const isAttached = (look: Look): boolean => look.attachedBy !== null; |
| 257 | 315 |
src/core/schema.ts +7
| @@ -1595,6 +1595,13 @@ export const migrations: readonly string[] = [ | ||
| 1595 | 1595 | PRIMARY KEY (repo_id, parent_id, issue_id) |
| 1596 | 1596 | ); |
| 1597 | 1597 | `, |
| 1598 | // 76 — how many times in a row a picture has failed (#1150), so the | |
| 1599 | // retry waits double: the look sweep reads it with \`created_at\`. | |
| 1600 | ` | |
| 1601 | ALTER TABLE look ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0; | |
| 1602 | UPDATE look SET attempts = 1 WHERE error IS NOT NULL; | |
| 1603 | ||
| 1604 | `, | |
| 1598 | 1605 | ]; |
| 1599 | 1606 | |
| 1600 | 1607 | /** |
src/looks/capture.ts +44 −3
| @@ -29,6 +29,7 @@ import { | ||
| 29 | 29 | existsSync, |
| 30 | 30 | mkdtempSync, |
| 31 | 31 | openSync, |
| 32 | readFileSync, | |
| 32 | 33 | readSync, |
| 33 | 34 | rmSync, |
| 34 | 35 | statSync, |
| @@ -37,6 +38,7 @@ import { tmpdir } from "node:os"; | ||
| 37 | 38 | import { join } from "node:path"; |
| 38 | 39 | import { childEnv } from "../apps/process.ts"; |
| 39 | 40 | import { Gate } from "../git/env.ts"; |
| 41 | import { decodePng } from "../design/image/png.ts"; | |
| 40 | 42 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 41 | 43 | |
| 42 | 44 | export interface LookInput { |
| @@ -112,9 +114,43 @@ function pictureDone(path: string): boolean { | ||
| 112 | 114 | } |
| 113 | 115 | } |
| 114 | 116 | |
| 117 | /** | |
| 118 | * A page that draws after load (a game's canvas) is a blank first paint. | |
| 119 | * One taken uniform is waited on longer and taken again; the second is kept | |
| 120 | * whatever it is, since a page may be one colour on purpose. | |
| 121 | */ | |
| 115 | 122 | async function shoot( |
| 116 | 123 | binary: string, |
| 117 | 124 | input: LookInput, |
| 125 | ): Promise<Result<void, string>> { | |
| 126 | const first = await shootOnce(binary, input, LOAD_MS); | |
| 127 | if (!first.ok || !blank(input.out)) return first; | |
| 128 | return shootOnce(binary, input, LOAD_MS * 3); | |
| 129 | } | |
| 130 | ||
| 131 | /** Whether a picture on disk is one flat colour. */ | |
| 132 | export function blank(path: string): boolean { | |
| 133 | try { | |
| 134 | const decoded = decodePng(new Uint8Array(readFileSync(path))); | |
| 135 | if (!decoded.ok) return false; | |
| 136 | const { rgba } = decoded.value; | |
| 137 | for (let i = 4; i < rgba.length; i += 4) | |
| 138 | if ( | |
| 139 | rgba[i] !== rgba[0] || | |
| 140 | rgba[i + 1] !== rgba[1] || | |
| 141 | rgba[i + 2] !== rgba[2] | |
| 142 | ) | |
| 143 | return false; | |
| 144 | return true; | |
| 145 | } catch { | |
| 146 | return false; | |
| 147 | } | |
| 148 | } | |
| 149 | ||
| 150 | async function shootOnce( | |
| 151 | binary: string, | |
| 152 | input: LookInput, | |
| 153 | loadMs: number, | |
| 118 | 154 | ): Promise<Result<void, string>> { |
| 119 | 155 | const host = new URL(input.url).hostname; |
| 120 | 156 | // A profile of its own, gone afterwards: no cookie outlives its picture, |
| @@ -139,11 +175,16 @@ async function shoot( | ||
| 139 | 175 | "--no-first-run", |
| 140 | 176 | `--user-data-dir=${profile}`, |
| 141 | 177 | // The app's hostname is the forge's own listener: no DNS, no edge. |
| 142 | `--host-resolver-rules=MAP ${host} 127.0.0.1`, | |
| 178 | // Every other name is unresolvable: a hop to a public name this pod | |
| 179 | // resolves differently from the world (the forge's own sign-in, behind | |
| 180 | // a certificate Chromium does not trust) fails rather than pictures | |
| 181 | // someone else's page. | |
| 182 | `--host-resolver-rules=MAP ${host} 127.0.0.1, MAP * ~NOTFOUND, EXCLUDE 127.0.0.1`, | |
| 183 | "--run-all-compositor-stages-before-draw", | |
| 143 | 184 | `--window-size=${input.width},${input.height}`, |
| 144 | 185 | "--force-device-scale-factor=1", |
| 145 | 186 | "--js-flags=--max-old-space-size=256", |
| 146 | `--timeout=${LOAD_MS}`, | |
| 187 | `--timeout=${loadMs}`, | |
| 147 | 188 | `--screenshot=${input.out}`, |
| 148 | 189 | input.url, |
| 149 | 190 | ], |
| @@ -168,7 +209,7 @@ async function shoot( | ||
| 168 | 209 | said.push(decoder.decode(value, { stream: true })); |
| 169 | 210 | } |
| 170 | 211 | })().catch(() => {}); |
| 171 | const deadline = Date.now() + input.timeoutMs; | |
| 212 | const deadline = Date.now() + input.timeoutMs + loadMs - LOAD_MS; | |
| 172 | 213 | try { |
| 173 | 214 | for (;;) { |
| 174 | 215 | if (pictureDone(input.out)) return ok(); |
src/looks/preflight.ts added +85
| @@ -0,0 +1,85 @@ | ||
| 1 | /** | |
| 2 | * Walking to a page before the browser does. The browser pictures wherever | |
| 3 | * it lands, and what it landed on is no business of a picture: a sign-in | |
| 4 | * page, a browser's own certificate error, an app that answered 404. So the | |
| 5 | * forge makes the same journey first, over its own listener, hop by hop — | |
| 6 | * and a hop that leaves it (a public name this pod resolves to somewhere | |
| 7 | * else) or ends on something that is not the app is a failed look with a | |
| 8 | * reason, never a picture. | |
| 9 | */ | |
| 10 | ||
| 11 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 12 | ||
| 13 | /** Walks a look's URL; ok when the end of the road is the app's page. */ | |
| 14 | export type Preflight = (url: string) => Promise<Result<void, string>>; | |
| 15 | ||
| 16 | const MAX_HOPS = 6; | |
| 17 | /** Enough of a page to read its title. */ | |
| 18 | const TITLE_BYTES = 32_768; | |
| 19 | ||
| 20 | /** Titles of pages that are not the app: a browser's error, the forge's door. */ | |
| 21 | const NOT_THE_APP = /^(privacy error|your connection is not private|sign in\b)/i; | |
| 22 | ||
| 23 | /** | |
| 24 | * `url` names the app's host on the forge's own port; the request goes to | |
| 25 | * the loopback with that host in its Host header, exactly as the browser's | |
| 26 | * host-resolver rule sends it. | |
| 27 | */ | |
| 28 | export function walkDoor( | |
| 29 | fetcher: typeof fetch = fetch, | |
| 30 | ): Preflight { | |
| 31 | return async (url) => { | |
| 32 | const start = new URL(url); | |
| 33 | const cookies = new Map<string, string>(); | |
| 34 | let at = start; | |
| 35 | for (let hop = 0; hop <= MAX_HOPS; hop++) { | |
| 36 | if ( | |
| 37 | at.protocol !== "http:" || | |
| 38 | at.hostname !== start.hostname || | |
| 39 | at.port !== start.port | |
| 40 | ) | |
| 41 | return err(`left the forge (${at.protocol}//${at.host})`); | |
| 42 | let res: Response; | |
| 43 | try { | |
| 44 | res = await fetcher( | |
| 45 | `http://127.0.0.1:${start.port}${at.pathname}${at.search}`, | |
| 46 | { | |
| 47 | redirect: "manual", | |
| 48 | headers: { | |
| 49 | host: at.host, | |
| 50 | cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join("; "), | |
| 51 | }, | |
| 52 | signal: AbortSignal.timeout(10_000), | |
| 53 | }, | |
| 54 | ); | |
| 55 | } catch (error) { | |
| 56 | return err(`the door did not answer: ${String(error).slice(0, 120)}`); | |
| 57 | } | |
| 58 | for (const line of res.headers.getSetCookie()) { | |
| 59 | const [pair = ""] = line.split(";"); | |
| 60 | const eq = pair.indexOf("="); | |
| 61 | if (eq > 0) cookies.set(pair.slice(0, eq).trim(), pair.slice(eq + 1)); | |
| 62 | } | |
| 63 | if (res.status >= 300 && res.status < 400) { | |
| 64 | const to = res.headers.get("location"); | |
| 65 | if (to === null) return err(`redirected nowhere (${res.status})`); | |
| 66 | try { | |
| 67 | at = new URL(to, at); | |
| 68 | } catch { | |
| 69 | return err("redirected to an address that is not one"); | |
| 70 | } | |
| 71 | await res.body?.cancel().catch(() => {}); | |
| 72 | continue; | |
| 73 | } | |
| 74 | if (res.status === 404) return err("not serving"); | |
| 75 | if (res.status >= 400) return err(`the app answered ${res.status}`); | |
| 76 | if (/^\/sign(in|up)\b/.test(at.pathname)) | |
| 77 | return err("ended on the forge's sign-in page"); | |
| 78 | const text = (await res.text()).slice(0, TITLE_BYTES); | |
| 79 | const title = /<title[^>]*>([^<]*)/i.exec(text)?.[1]?.trim() ?? ""; | |
| 80 | if (NOT_THE_APP.test(title)) return err(`ended on "${title.slice(0, 60)}"`); | |
| 81 | return ok(); | |
| 82 | } | |
| 83 | return err("too many redirects"); | |
| 84 | }; | |
| 85 | } |
src/looks/service.ts +107 −19
| @@ -49,7 +49,10 @@ import { | ||
| 49 | 49 | LOOK_WINDOWS, |
| 50 | 50 | lookSlot, |
| 51 | 51 | looksForEnv, |
| 52 | getLook, | |
| 52 | 53 | recordLook, |
| 54 | retryAt, | |
| 55 | staleThumb, | |
| 53 | 56 | type Look, |
| 54 | 57 | type LookKind, |
| 55 | 58 | } from "../core/looks.ts"; |
| @@ -62,6 +65,7 @@ import { decodePng, encodePng, pngHeader } from "../design/image/png.ts"; | ||
| 62 | 65 | import { createLog } from "../kernel/log.ts"; |
| 63 | 66 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 64 | 67 | import { findChromium, takeLook, type Capture } from "./capture.ts"; |
| 68 | import { walkDoor, type Preflight } from "./preflight.ts"; | |
| 65 | 69 | |
| 66 | 70 | const log = createLog("looks"); |
| 67 | 71 | |
| @@ -70,6 +74,8 @@ export interface LooksOptions { | ||
| 70 | 74 | readonly localUrl: string; |
| 71 | 75 | /** What takes the picture. Chromium unless a test says otherwise. */ |
| 72 | 76 | readonly capture?: Capture | undefined; |
| 77 | /** Walks the road to the page before the browser does; the forge's own listener unless a test says otherwise. */ | |
| 78 | readonly preflight?: Preflight | undefined; | |
| 73 | 79 | /** |
| 74 | 80 | * How full the process's memory is, 0 to 1, or undefined when unknown. |
| 75 | 81 | * The container's cgroup unless a test says otherwise. A browser is the |
| @@ -194,7 +200,7 @@ interface Pending { | ||
| 194 | 200 | readonly env: EnvName; |
| 195 | 201 | readonly commitOid: string; |
| 196 | 202 | readonly at: number; |
| 197 | /** Queued by the sweep: a picture that failed at this head is not retaken. */ | |
| 203 | /** Queued by the sweep: a failed picture waits for its retry time. */ | |
| 198 | 204 | readonly swept?: true; |
| 199 | 205 | } |
| 200 | 206 | |
| @@ -202,6 +208,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 202 | 208 | const { dataDir } = app.config; |
| 203 | 209 | const port = new URL(options.localUrl).port; |
| 204 | 210 | const capture = options.capture ?? takeLook; |
| 211 | const preflight = options.preflight ?? walkDoor(); | |
| 205 | 212 | if (options.capture === undefined && findChromium() === undefined) |
| 206 | 213 | log.warn( |
| 207 | 214 | "no chromium on this forge: looks will say so instead of a picture (install one, or set FORGE_CHROMIUM)", |
| @@ -263,6 +270,24 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 263 | 270 | enqueue({ appId: record.id, env, commitOid, at: Date.now() }); |
| 264 | 271 | return; |
| 265 | 272 | } |
| 273 | // An app's access changed: every picture of it was taken as someone | |
| 274 | // the app no longer treats that way. `missing` sees the difference; | |
| 275 | // this queues the environments that are up to be looked at again. | |
| 276 | case "app.updated": { | |
| 277 | const record = getAppByRepo(app.db, event.repoId); | |
| 278 | const runtime = appsRuntime(app); | |
| 279 | if (!record || runtime === undefined) return; | |
| 280 | for (const s of runtime.status(record)) | |
| 281 | if (s.state === "running") | |
| 282 | enqueue({ | |
| 283 | appId: record.id, | |
| 284 | env: s.env, | |
| 285 | commitOid: s.commitOid, | |
| 286 | at: Date.now(), | |
| 287 | swept: true, | |
| 288 | }); | |
| 289 | return; | |
| 290 | } | |
| 266 | 291 | case "pull.closed": |
| 267 | 292 | case "pull.merged": { |
| 268 | 293 | const number = payload["number"]; |
| @@ -358,11 +383,8 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 358 | 383 | // A sealed pull's preview is its report's (`core/sealed.ts`): nobody can |
| 359 | 384 | // open it, so every picture of it is taken as the owner, and kept for |
| 360 | 385 | // the writers. |
| 361 | const sealed = sealedPreview(app.db, repo.id, item.env); | |
| 362 | const everyone = | |
| 363 | !sealed && repo.visibility === "public" && record.access === "public"; | |
| 364 | const asNobody = (kind: LookKind): boolean => | |
| 365 | !sealed && (everyone || kind === "thumb"); | |
| 386 | const expectedAs = viewOf(record, repo, item.env); | |
| 387 | const asNobody = (kind: LookKind): boolean => expectedAs(kind) === "nobody"; | |
| 366 | 388 | const owner = getUserById(app.db, repo.ownerId); |
| 367 | 389 | const asOwner: GrantWho | undefined = |
| 368 | 390 | owner === undefined |
| @@ -391,12 +413,17 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 391 | 413 | `${item.appId}-${item.env}-${item.commitOid}-${lookSlot(page, kind)}.png`, |
| 392 | 414 | ); |
| 393 | 415 | mkdirSync(dirname(staged), { recursive: true }); |
| 394 | const shot = await capture({ | |
| 395 | url, | |
| 396 | out: staged, | |
| 397 | ...LOOK_WINDOWS[kind], | |
| 398 | timeoutMs: CAPTURE_TIMEOUT_MS, | |
| 399 | }); | |
| 416 | // Walk the road first: a sign-in page, a hop off the forge or an app | |
| 417 | // that is not serving is a reason, not a picture. | |
| 418 | const road = await preflight(url); | |
| 419 | const shot = road.ok | |
| 420 | ? await capture({ | |
| 421 | url, | |
| 422 | out: staged, | |
| 423 | ...LOOK_WINDOWS[kind], | |
| 424 | timeoutMs: CAPTURE_TIMEOUT_MS, | |
| 425 | }) | |
| 426 | : road; | |
| 400 | 427 | const taken = |
| 401 | 428 | shot.ok && kind === "thumb" ? reduceToThumb(staged) : shot; |
| 402 | 429 | const row = { |
| @@ -428,6 +455,34 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 428 | 455 | } else { |
| 429 | 456 | rmSync(staged, { force: true }); |
| 430 | 457 | allOk = false; |
| 458 | // A retake that fails keeps the picture it was to replace, when that | |
| 459 | // one is still the right view (a stale thumb): never an empty card | |
| 460 | // for want of a fresh one. | |
| 461 | const prior = getLook( | |
| 462 | app.db, | |
| 463 | item.appId, | |
| 464 | item.env, | |
| 465 | item.commitOid, | |
| 466 | page, | |
| 467 | kind, | |
| 468 | ); | |
| 469 | if ( | |
| 470 | prior !== undefined && | |
| 471 | prior.error === null && | |
| 472 | keepLook(dataDir, prior) && | |
| 473 | prior.takenAs === expectedAs(kind) | |
| 474 | ) { | |
| 475 | log.warn("retake failed; keeping the picture", { | |
| 476 | app: record.slug, | |
| 477 | env: item.env, | |
| 478 | page, | |
| 479 | kind, | |
| 480 | error: taken.error, | |
| 481 | }); | |
| 482 | continue; | |
| 483 | } | |
| 484 | if (prior !== undefined && prior.path !== "") | |
| 485 | rmSync(join(dataDir, prior.path), { force: true }); | |
| 431 | 486 | log.warn("no picture", { |
| 432 | 487 | app: record.slug, |
| 433 | 488 | env: item.env, |
| @@ -450,6 +505,28 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 450 | 505 | }); |
| 451 | 506 | } |
| 452 | 507 | |
| 508 | /** | |
| 509 | * Who each kind of picture is taken as. A sealed pull's preview is the | |
| 510 | * owner's (nobody can open it). A public app on a public repository is | |
| 511 | * the world's to see, so all of its pictures are taken as nobody. The | |
| 512 | * thumb of any public app is too — it is the tile a stranger is shown — | |
| 513 | * but a thumb of an app that is not public is the owner's: a stranger is | |
| 514 | * sent to the forge's sign-in, and that is not what the app looks like. | |
| 515 | */ | |
| 516 | function viewOf( | |
| 517 | record: AppRecord, | |
| 518 | repo: { id: string; visibility: string }, | |
| 519 | env: EnvName, | |
| 520 | ): (kind: LookKind) => "owner" | "nobody" { | |
| 521 | const sealed = sealedPreview(app.db, repo.id, env); | |
| 522 | const everyone = | |
| 523 | !sealed && repo.visibility === "public" && record.access === "public"; | |
| 524 | return (kind) => | |
| 525 | !sealed && (everyone || (kind === "thumb" && record.access === "public")) | |
| 526 | ? "nobody" | |
| 527 | : "owner"; | |
| 528 | } | |
| 529 | ||
| 453 | 530 | /** |
| 454 | 531 | * The pictures one head still wants: every page at every kind, less |
| 455 | 532 | * those on record to keep — and, when `failedCounts`, less those that |
| @@ -462,13 +539,24 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 462 | 539 | pages: readonly string[] | undefined, |
| 463 | 540 | failedCounts = false, |
| 464 | 541 | ): { page: string; kind: LookKind }[] { |
| 542 | const now = Date.now(); | |
| 543 | const record = getAppById(app.db, appId); | |
| 544 | const repo = record && getRepoById(app.db, record.repoId); | |
| 545 | const expectedAs = | |
| 546 | record && repo ? viewOf(record, repo, env) : undefined; | |
| 465 | 547 | const have = new Set( |
| 466 | 548 | looksForEnv(app.db, appId, env) |
| 467 | .filter( | |
| 468 | (l) => | |
| 469 | l.commitOid === commitOid && | |
| 470 | (keepLook(dataDir, l) || (failedCounts && l.error !== null)), | |
| 471 | ) | |
| 549 | .filter((l) => { | |
| 550 | if (l.commitOid !== commitOid) return false; | |
| 551 | // A failed picture waits out its backoff, then is tried again. | |
| 552 | if (l.error !== null) return failedCounts && now < (retryAt(l) ?? 0); | |
| 553 | if (!keepLook(dataDir, l)) return false; | |
| 554 | // Taken as someone the app no longer treats that way. | |
| 555 | if (expectedAs !== undefined && l.takenAs !== expectedAs(l.kind)) | |
| 556 | return false; | |
| 557 | // A week-old thumb of a running production is retaken. | |
| 558 | return !(env === "production" && staleThumb(l, now)); | |
| 559 | }) | |
| 472 | 560 | .map((l) => lookSlot(l.page, l.kind)), |
| 473 | 561 | ); |
| 474 | 562 | return (pages ?? [DEFAULT_PAGE]).flatMap((page) => |
| @@ -501,8 +589,8 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 501 | 589 | ) |
| 502 | 590 | toWake.push(record); |
| 503 | 591 | if (status?.state !== "running") continue; |
| 504 | // A picture that failed at this head had its turn: the next | |
| 505 | // deploy tries again, not every sweep. | |
| 592 | // A picture that failed at this head waits out its backoff | |
| 593 | // (`retryAt`), then is tried again. | |
| 506 | 594 | const { commitOid, looks: pages } = status; |
| 507 | 595 | if (missing(record.id, "production", commitOid, pages, true).length > 0) |
| 508 | 596 | enqueue({ |
src/web/studio/home.ts +27 −16
| @@ -221,22 +221,29 @@ export async function studioHome( | ||
| 221 | 221 | } |
| 222 | 222 | |
| 223 | 223 | /** |
| 224 | * A shelf tile: picture, name, one clamped line, how it is. The shelf | |
| 225 | * holds only apps with a picture (`frontPage`), so there is no tile | |
| 226 | * without one. | |
| 224 | * A shelf tile: picture, name, one clamped line, how it is. A tile with no | |
| 225 | * picture says why, or sets the app's name on a calm ground. | |
| 227 | 226 | */ |
| 228 | function tile(entry: FrontEntry): Html { | |
| 229 | const { repo, state, picture } = entry; | |
| 230 | if (picture === undefined) return html``; | |
| 227 | export function tile(entry: FrontEntry): Html { | |
| 228 | const { repo, state, picture, reason } = entry; | |
| 229 | // Never a question mark: the one line the forge has about the picture, | |
| 230 | // or the app's name, set well on a calm ground. | |
| 231 | const look = | |
| 232 | picture === undefined | |
| 233 | ? html`<span | |
| 234 | class="app-tile-look app-tile-calm" | |
| 235 | ><b>${repo.name}</b>${when(reason, (r) => html`<small>${r}</small>`)}</span | |
| 236 | >` | |
| 237 | : html`<img | |
| 238 | class="app-tile-look" | |
| 239 | src="${picture}" | |
| 240 | width="${LOOK_SIZES.thumb.width}" | |
| 241 | height="${LOOK_SIZES.thumb.height}" | |
| 242 | alt="" | |
| 243 | loading="lazy" | |
| 244 | />`; | |
| 231 | 245 | return html`<a class="app-tile" href="${repoBase(repo)}"> |
| 232 | <img | |
| 233 | class="app-tile-look" | |
| 234 | src="${picture}" | |
| 235 | width="${LOOK_SIZES.thumb.width}" | |
| 236 | height="${LOOK_SIZES.thumb.height}" | |
| 237 | alt="" | |
| 238 | loading="lazy" | |
| 239 | /> | |
| 246 | ${look} | |
| 240 | 247 | <span class="app-tile-body"> |
| 241 | 248 | <span class="app-tile-name">${repo.name}</span> |
| 242 | 249 | <span class="app-tile-desc truncate" title="${repo.description}" |
| @@ -252,8 +259,8 @@ function tile(entry: FrontEntry): Html { | ||
| 252 | 259 | * the crew at work on it right now, by issue; or, when nobody is, when it |
| 253 | 260 | * last shipped. |
| 254 | 261 | */ |
| 255 | function featuredCard(featured: NonNullable<FrontPage["featured"]>): Html { | |
| 256 | const { repo, picture, crew, signals } = featured; | |
| 262 | export function featuredCard(featured: NonNullable<FrontPage["featured"]>): Html { | |
| 263 | const { repo, picture, reason, crew, signals } = featured; | |
| 257 | 264 | const base = repoBase(repo); |
| 258 | 265 | const agents = `${crew.running} agent${crew.running === 1 ? "" : "s"}`; |
| 259 | 266 | const work = |
| @@ -295,6 +302,10 @@ function featuredCard(featured: NonNullable<FrontPage["featured"]>): Html { | ||
| 295 | 302 | <span class="small muted">Featured</span> |
| 296 | 303 | <h2><a href="${base}">${repo.ownerName}/${repo.name}</a></h2> |
| 297 | 304 | ${when(repo.description, (d) => html`<p>${d}</p>`)} ${work} |
| 305 | ${when( | |
| 306 | picture === undefined ? reason : undefined, | |
| 307 | (r) => html`<p class="small muted front-reason">No picture: ${r}.</p>`, | |
| 308 | )} | |
| 298 | 309 | <div class="bar">${btn("Open", { href: base, variant: "primary" })}</div> |
| 299 | 310 | </div> |
| 300 | 311 | </section>`; |
src/web/style/content.ts +3
| @@ -444,6 +444,9 @@ form.inline { display: inline; margin-left: auto; } | ||
| 444 | 444 | } |
| 445 | 445 | .app-tile:hover { border-color: var(--accent); } |
| 446 | 446 | .app-tile-look { display: block; width: 100%; height: auto; background: var(--muted); } |
| 447 | .app-tile-calm { aspect-ratio: 8 / 5; display: grid; place-content: center; gap: 4px; width: 100%; text-align: center; padding: 12px; background: var(--muted); color: var(--muted-fg); } | |
| 448 | .app-tile-calm b { font-size: 20px; letter-spacing: -0.02em; color: var(--fg); overflow-wrap: anywhere; } | |
| 449 | .app-tile-calm small { font-size: 12px; } | |
| 447 | 450 | .app-tile-body { display: grid; gap: 6px; padding: 10px 12px; } |
| 448 | 451 | .app-tile-name { font-weight: 600; font-size: 14px; } |
| 449 | 452 | .app-tile-desc { color: var(--muted-fg); font-size: 12.5px; } |
test/front.test.ts +1
| @@ -578,6 +578,7 @@ describe("the front page", () => { | ||
| 578 | 578 | // picture is taken as nobody; then it takes its place. |
| 579 | 579 | const looks = startLooks(app, { |
| 580 | 580 | localUrl: servers.url, |
| 581 | preflight: async () => ({ ok: true, value: undefined }), | |
| 581 | 582 | capture: async (input) => { |
| 582 | 583 | writeFileSync(input.out, Buffer.from(encodePng(4, 4, new Uint8Array(64).fill(255)))); |
| 583 | 584 | return { ok: true, value: undefined }; |
test/looks-reasons.test.ts added +187
| @@ -0,0 +1,187 @@ | ||
| 1 | /** | |
| 2 | * The parts of the look that need no browser and no server (#1150): when a | |
| 3 | * failed picture is tried again, what a card without a picture says, and | |
| 4 | * how the road to a page is walked before the browser is sent down it. | |
| 5 | */ | |
| 6 | ||
| 7 | import { describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { | |
| 12 | lookReason, | |
| 13 | retryAt, | |
| 14 | RETRY_MAX_MS, | |
| 15 | staleThumb, | |
| 16 | type Look, | |
| 17 | } from "../src/core/looks.ts"; | |
| 18 | import { encodePng } from "../src/design/image/png.ts"; | |
| 19 | import { blank } from "../src/looks/capture.ts"; | |
| 20 | import { walkDoor } from "../src/looks/preflight.ts"; | |
| 21 | ||
| 22 | const NOW = Date.parse("2026-10-14T20:00:00Z"); | |
| 23 | ||
| 24 | const look = (over: Partial<Look> = {}): Look => ({ | |
| 25 | id: "l", | |
| 26 | appId: "a", | |
| 27 | env: "production", | |
| 28 | commitOid: "0".repeat(40), | |
| 29 | page: "/", | |
| 30 | kind: "thumb", | |
| 31 | path: "", | |
| 32 | createdAt: "2026-10-14T20:00:00.000Z", | |
| 33 | error: null, | |
| 34 | takenAs: "nobody", | |
| 35 | attempts: 0, | |
| 36 | attachedBy: null, | |
| 37 | note: null, | |
| 38 | ...over, | |
| 39 | }); | |
| 40 | ||
| 41 | describe("when a failed picture is tried again", () => { | |
| 42 | test("the wait doubles from five minutes and stops at a day", () => { | |
| 43 | const wait = (attempts: number): number => | |
| 44 | retryAt(look({ error: "x", attempts }))! - NOW; | |
| 45 | expect(wait(1)).toBe(5 * 60_000); | |
| 46 | expect(wait(2)).toBe(10 * 60_000); | |
| 47 | expect(wait(3)).toBe(20 * 60_000); | |
| 48 | expect(wait(40)).toBe(RETRY_MAX_MS); | |
| 49 | expect(retryAt(look())).toBeUndefined(); | |
| 50 | }); | |
| 51 | ||
| 52 | test("a thumb is stale after a week, a phone picture never", () => { | |
| 53 | const week = 7 * 24 * 3_600_000; | |
| 54 | expect(staleThumb(look(), NOW + week - 1000)).toBe(false); | |
| 55 | expect(staleThumb(look(), NOW + week + 1000)).toBe(true); | |
| 56 | expect(staleThumb(look({ kind: "phone" }), NOW + 2 * week)).toBe(false); | |
| 57 | expect(staleThumb(look({ error: "x" }), NOW + 2 * week)).toBe(false); | |
| 58 | }); | |
| 59 | }); | |
| 60 | ||
| 61 | describe("what a card with no picture says", () => { | |
| 62 | const say = (over: Parameters<typeof lookReason>[0]) => lookReason(over); | |
| 63 | test("each state has its line, and nothing to say is nothing", () => { | |
| 64 | const base = { state: "running", thumb: undefined, writersOnly: false, now: NOW }; | |
| 65 | expect(say(base)).toBe("taking a picture"); | |
| 66 | expect(say({ ...base, state: "failed" })).toBe("not serving"); | |
| 67 | expect(say({ ...base, state: "deploying" })).toBe("taking a picture once it is up"); | |
| 68 | expect(say({ ...base, writersOnly: true })).toBe( | |
| 69 | "pictures are the writers' on this private app", | |
| 70 | ); | |
| 71 | expect(say({ ...base, state: undefined })).toBeUndefined(); | |
| 72 | expect( | |
| 73 | say({ | |
| 74 | ...base, | |
| 75 | thumb: look({ error: "chromium exited 1: secret detail", attempts: 1 }), | |
| 76 | }), | |
| 77 | ).toBe("failed; retrying at 20:05 UTC"); | |
| 78 | // The browser's own words are never a stranger's to read. | |
| 79 | expect( | |
| 80 | say({ ...base, thumb: look({ error: "chromium exited 1: secret detail" }) }), | |
| 81 | ).not.toContain("secret"); | |
| 82 | }); | |
| 83 | }); | |
| 84 | ||
| 85 | describe("the road to a page", () => { | |
| 86 | const url = "http://app.apps.test:3000/__forge/grant?t=x&to=%2F"; | |
| 87 | const road = (steps: Response[]) => { | |
| 88 | const seen: { url: string; host: string | null; cookie: string | null }[] = []; | |
| 89 | const fetcher = (async (input: string | URL | Request, init?: RequestInit) => { | |
| 90 | const headers = new Headers(init?.headers); | |
| 91 | seen.push({ url: String(input), host: headers.get("host"), cookie: headers.get("cookie") }); | |
| 92 | return steps.shift()!; | |
| 93 | }) as typeof fetch; | |
| 94 | return { walk: walkDoor(fetcher), seen }; | |
| 95 | }; | |
| 96 | const redirect = (to: string, cookie?: string): Response => | |
| 97 | new Response(null, { | |
| 98 | status: 302, | |
| 99 | headers: cookie === undefined ? { location: to } : { location: to, "set-cookie": cookie }, | |
| 100 | }); | |
| 101 | const page = (title: string, status = 200): Response => | |
| 102 | new Response(`<html><title>${title}</title></html>`, { status }); | |
| 103 | ||
| 104 | test("the app's page, reached with the grant's cookie, is a clear road — over the loopback with the app's host", async () => { | |
| 105 | const { walk, seen } = road([redirect("/", "forge_grant=abc; Path=/; HttpOnly"), page("Hello")]); | |
| 106 | expect((await walk(url)).ok).toBe(true); | |
| 107 | expect(seen[0]!.url.startsWith("http://127.0.0.1:3000/__forge/grant")).toBe(true); | |
| 108 | expect(seen[0]!.host).toBe("app.apps.test:3000"); | |
| 109 | expect(seen[1]!.cookie).toBe("forge_grant=abc"); | |
| 110 | }); | |
| 111 | ||
| 112 | test("a hop to the forge's public name is refused as having left the forge", async () => { | |
| 113 | const { walk } = road([redirect("https://git.open-platform.sh/signin?next=%2F")]); | |
| 114 | const result = await walk(url); | |
| 115 | expect(result).toEqual({ ok: false, error: "left the forge (https://git.open-platform.sh)" }); | |
| 116 | }); | |
| 117 | ||
| 118 | test("a 404 is not serving; a browser's error page and the forge's sign-in are not pictures", async () => { | |
| 119 | expect(await road([redirect("/"), new Response("", { status: 404 })]).walk(url)).toEqual({ | |
| 120 | ok: false, | |
| 121 | error: "not serving", | |
| 122 | }); | |
| 123 | const err = await road([page("Privacy error")]).walk(url); | |
| 124 | expect(!err.ok && err.error).toContain("Privacy error"); | |
| 125 | const door = await road([redirect("/signin?next=/"), page("Hello")]).walk(url); | |
| 126 | expect(!door.ok && door.error).toContain("sign-in"); | |
| 127 | const bad = await road([page("Oops", 502)]).walk(url); | |
| 128 | expect(!bad.ok && bad.error).toBe("the app answered 502"); | |
| 129 | }); | |
| 130 | ||
| 131 | test("a road that never ends is refused", async () => { | |
| 132 | const hops = Array.from({ length: 9 }, () => redirect("/again")); | |
| 133 | const result = await road(hops).walk(url); | |
| 134 | expect(result).toEqual({ ok: false, error: "too many redirects" }); | |
| 135 | }); | |
| 136 | }); | |
| 137 | ||
| 138 | describe("a blank first paint", () => { | |
| 139 | test("one flat colour is blank; a mark on it is not", () => { | |
| 140 | const dir = mkdtempSync(join(tmpdir(), "forge-blank-")); | |
| 141 | try { | |
| 142 | const flat = new Uint8Array(8 * 8 * 4).fill(255); | |
| 143 | writeFileSync(join(dir, "a.png"), encodePng(8, 8, flat)); | |
| 144 | expect(blank(join(dir, "a.png"))).toBe(true); | |
| 145 | flat[40] = 0; | |
| 146 | writeFileSync(join(dir, "b.png"), encodePng(8, 8, flat)); | |
| 147 | expect(blank(join(dir, "b.png"))).toBe(false); | |
| 148 | expect(blank(join(dir, "missing.png"))).toBe(false); | |
| 149 | } finally { | |
| 150 | rmSync(dir, { recursive: true, force: true }); | |
| 151 | } | |
| 152 | }); | |
| 153 | }); | |
| 154 | ||
| 155 | describe("the card", () => { | |
| 156 | const entry = (over: Record<string, unknown>) => | |
| 157 | ({ | |
| 158 | repo: { name: "cs-engine", ownerName: "owner", description: "", id: "r" }, | |
| 159 | app: undefined, | |
| 160 | state: "running", | |
| 161 | picture: undefined, | |
| 162 | reason: "taking a picture", | |
| 163 | pinned: true, | |
| 164 | signals: { awakeHours: 0, ships: 0, forks: 0, shippedAt: null }, | |
| 165 | score: 0, | |
| 166 | crew: { running: 0, issues: [] }, | |
| 167 | ...over, | |
| 168 | }) as never; | |
| 169 | ||
| 170 | test("a tile with no picture shows its reason and the app's name, never an image", async () => { | |
| 171 | const { tile, featuredCard } = await import("../src/web/studio/home.ts"); | |
| 172 | const shown = tile(entry({})).toString(); | |
| 173 | expect(shown).toContain("app-tile-calm"); | |
| 174 | expect(shown).toContain("cs-engine"); | |
| 175 | expect(shown).toContain("taking a picture"); | |
| 176 | expect(shown).not.toContain("<img"); | |
| 177 | const named = tile(entry({ reason: undefined })).toString(); | |
| 178 | expect(named).toContain("cs-engine"); | |
| 179 | expect(named).not.toContain("<small>"); | |
| 180 | expect(tile(entry({ picture: "/x.png" })).toString()).toContain("<img"); | |
| 181 | expect(featuredCard(entry({ reason: "not serving" })).toString()).toContain( | |
| 182 | "No picture: not serving.", | |
| 183 | ); | |
| 184 | const escaped = tile(entry({ reason: "<b>x</b>" })).toString(); | |
| 185 | expect(escaped).not.toContain("<b>x</b>"); | |
| 186 | }); | |
| 187 | }); |
test/looks.test.ts +145 −7
| @@ -40,6 +40,7 @@ import { | ||
| 40 | 40 | type Capture, |
| 41 | 41 | type LookInput, |
| 42 | 42 | } from "../src/looks/capture.ts"; |
| 43 | import type { Preflight } from "../src/looks/preflight.ts"; | |
| 43 | 44 | import { startLooks, type LooksHandle } from "../src/looks/service.ts"; |
| 44 | 45 | |
| 45 | 46 | quietLogs(); |
| @@ -79,6 +80,8 @@ describe("the look", () => { | ||
| 79 | 80 | // The stand-in browser: writes a picture, or falls over, as told. |
| 80 | 81 | let mode: "ok" | "fail" = "ok"; |
| 81 | 82 | const calls: LookInput[] = []; |
| 83 | // The stand-in road to the page: clear, or blocked with a reason. | |
| 84 | let road: Preflight = async () => ok(); | |
| 82 | 85 | const fake: Capture = async (input) => { |
| 83 | 86 | calls.push(input); |
| 84 | 87 | if (mode === "fail") return err("the browser fell over"); |
| @@ -149,7 +152,11 @@ describe("the look", () => { | ||
| 149 | 152 | concurrency: 2, |
| 150 | 153 | }); |
| 151 | 154 | await runtime.start(); |
| 152 | looks = startLooks(app, { localUrl: servers.url, capture: fake }); | |
| 155 | looks = startLooks(app, { | |
| 156 | localUrl: servers.url, | |
| 157 | capture: fake, | |
| 158 | preflight: (url) => road(url), | |
| 159 | }); | |
| 153 | 160 | const a = await createUser(app.db, { trusted: true, |
| 154 | 161 | username: "alice", |
| 155 | 162 | email: "[email protected]", |
| @@ -224,16 +231,15 @@ describe("the look", () => { | ||
| 224 | 231 | expect(pngSize(join(dataDir, thumb.path))).toEqual([640, 400]); |
| 225 | 232 | const desktop = rows.find((l) => l.kind === "desktop")!; |
| 226 | 233 | expect(pngSize(join(dataDir, desktop.path))).toEqual([1280, 800]); |
| 227 | // The thumb's grant names nobody: the tile a stranger is shown is the | |
| 228 | // page as a stranger sees it. | |
| 234 | // `hello` is a private app: a stranger would be sent to the forge's | |
| 235 | // sign-in, which is not what it looks like, so its thumb is the owner's. | |
| 229 | 236 | const thumbCall = calls.find((c) => c.out.endsWith("-thumb.png"))!; |
| 230 | 237 | const thumbGrant = readGrant( |
| 231 | 238 | dataDir, |
| 232 | 239 | new URL(thumbCall.url).searchParams.get("t") ?? "", |
| 233 | 240 | { app: record, env: "production" }, |
| 234 | 241 | ); |
| 235 | expect(thumbGrant).toBeDefined(); | |
| 236 | expect(thumbGrant?.who).toBeUndefined(); | |
| 242 | expect(thumbGrant?.who).toEqual({ id: alice.id, name: "alice", role: "admin" }); | |
| 237 | 243 | const url = new URL(phone.url); |
| 238 | 244 | expect(url.host).toBe(`hello.${DOMAIN}:${servers.port}`); |
| 239 | 245 | expect(url.pathname).toBe("/__forge/grant"); |
| @@ -692,8 +698,8 @@ describe("the look", () => { | ||
| 692 | 698 | readGrant(dataDir, new URL(retaken.url).searchParams.get("t") ?? "", { |
| 693 | 699 | app: record, |
| 694 | 700 | env: "production", |
| 695 | })?.who, | |
| 696 | ).toBeUndefined(); | |
| 701 | })?.who?.name, | |
| 702 | ).toBe("alice"); | |
| 697 | 703 | expect(pngSize(join(dataDir, thumbAtHead()!.path))).toEqual([640, 400]); |
| 698 | 704 | |
| 699 | 705 | // A whole set: nothing to take. |
| @@ -716,6 +722,138 @@ describe("the look", () => { | ||
| 716 | 722 | expect(calls).toHaveLength(before + 1); |
| 717 | 723 | }, 60_000); |
| 718 | 724 | |
| 725 | /** Age a picture's row: it was taken `ms` ago. */ | |
| 726 | const aged = (look: Look, ms: number): void => { | |
| 727 | app.db | |
| 728 | .query(`UPDATE look SET created_at = ?2 WHERE id = ?1`) | |
| 729 | .run(look.id, new Date(Date.now() - ms).toISOString()); | |
| 730 | }; | |
| 731 | const thumbRow = (head: string): Look | undefined => | |
| 732 | looksForEnv(app.db, record.id, "production").find( | |
| 733 | (l) => l.kind === "thumb" && l.commitOid === head && l.page === "/", | |
| 734 | ); | |
| 735 | ||
| 736 | test("a failed picture is retried on a doubling schedule, a thumb a week old is retaken, a failed retake keeps the picture, and an app that is not serving is skipped with its reason (#1150)", async () => { | |
| 737 | const head = runtime.envStatus(record, "production")!.commitOid; | |
| 738 | // The test before left this head's thumb failed; start from a clean slate. | |
| 739 | app.db.query(`DELETE FROM look WHERE app_id = ?1 AND kind = 'thumb'`).run(record.id); | |
| 740 | looks.sweep(); | |
| 741 | await looks.idle(); | |
| 742 | expect(thumbRow(head)!.error).toBeNull(); | |
| 743 | const MIN = 60_000; | |
| 744 | const failedTwice = (): Look => { | |
| 745 | for (let n = 0; n < 2; n++) | |
| 746 | recordLook(app.db, { | |
| 747 | appId: record.id, | |
| 748 | env: "production", | |
| 749 | commitOid: head, | |
| 750 | kind: "thumb", | |
| 751 | path: "", | |
| 752 | error: "failed under load", | |
| 753 | }); | |
| 754 | return thumbRow(head)!; | |
| 755 | }; | |
| 756 | ||
| 757 | // Failed once, six minutes ago: past the first wait (5 min), retried. | |
| 758 | recordLook(app.db, { | |
| 759 | appId: record.id, | |
| 760 | env: "production", | |
| 761 | commitOid: head, | |
| 762 | kind: "thumb", | |
| 763 | path: "", | |
| 764 | error: "failed under load", | |
| 765 | }); | |
| 766 | expect(thumbRow(head)!.attempts).toBe(1); | |
| 767 | let before = calls.length; | |
| 768 | looks.sweep(); | |
| 769 | await looks.idle(); | |
| 770 | expect(calls).toHaveLength(before); | |
| 771 | aged(thumbRow(head)!, 6 * MIN); | |
| 772 | looks.sweep(); | |
| 773 | await looks.idle(); | |
| 774 | expect(calls).toHaveLength(before + 1); | |
| 775 | expect(thumbRow(head)!.error).toBeNull(); | |
| 776 | expect(thumbRow(head)!.attempts).toBe(0); | |
| 777 | ||
| 778 | // Failed twice: the wait doubles to ten minutes. | |
| 779 | aged(failedTwice(), 6 * MIN); | |
| 780 | expect(thumbRow(head)!.attempts).toBe(2); | |
| 781 | before = calls.length; | |
| 782 | looks.sweep(); | |
| 783 | await looks.idle(); | |
| 784 | expect(calls).toHaveLength(before); | |
| 785 | aged(thumbRow(head)!, 11 * MIN); | |
| 786 | looks.sweep(); | |
| 787 | await looks.idle(); | |
| 788 | expect(calls).toHaveLength(before + 1); | |
| 789 | expect(thumbRow(head)!.error).toBeNull(); | |
| 790 | ||
| 791 | // A thumb a week old is retaken; one a day old is not. | |
| 792 | before = calls.length; | |
| 793 | aged(thumbRow(head)!, 24 * 3_600_000); | |
| 794 | looks.sweep(); | |
| 795 | await looks.idle(); | |
| 796 | expect(calls).toHaveLength(before); | |
| 797 | const old = thumbRow(head)!; | |
| 798 | aged(old, 8 * 24 * 3_600_000); | |
| 799 | looks.sweep(); | |
| 800 | await looks.idle(); | |
| 801 | expect(calls).toHaveLength(before + 1); | |
| 802 | expect(Date.parse(thumbRow(head)!.createdAt)).toBeGreaterThan(Date.now() - 60_000); | |
| 803 | ||
| 804 | // A retake that fails keeps the stale picture: no empty card for want | |
| 805 | // of a fresh one. | |
| 806 | aged(thumbRow(head)!, 8 * 24 * 3_600_000); | |
| 807 | mode = "fail"; | |
| 808 | looks.sweep(); | |
| 809 | await looks.idle(); | |
| 810 | mode = "ok"; | |
| 811 | expect(thumbRow(head)!.error).toBeNull(); | |
| 812 | expect(existsSync(join(dataDir, thumbRow(head)!.path))).toBe(true); | |
| 813 | ||
| 814 | // An app that answers 404 is not pictured: the browser is never started, | |
| 815 | // and the row says why. | |
| 816 | app.db.query(`DELETE FROM look WHERE id = ?1`).run(thumbRow(head)!.id); | |
| 817 | road = async () => err("not serving"); | |
| 818 | before = calls.length; | |
| 819 | looks.sweep(); | |
| 820 | await looks.idle(); | |
| 821 | road = async () => ok(); | |
| 822 | expect(calls).toHaveLength(before); | |
| 823 | expect(thumbRow(head)!.error).toBe("not serving"); | |
| 824 | ||
| 825 | // Once the road is clear and the wait is over, it is pictured again. | |
| 826 | aged(thumbRow(head)!, 6 * MIN); | |
| 827 | looks.sweep(); | |
| 828 | await looks.idle(); | |
| 829 | expect(thumbRow(head)!.error).toBeNull(); | |
| 830 | }, 60_000); | |
| 831 | ||
| 832 | test("an app whose access changes has its thumb retaken as the one it is now", async () => { | |
| 833 | const head = runtime.envStatus(record, "production")!.commitOid; | |
| 834 | expect(thumbRow(head)!.takenAs).toBe("owner"); | |
| 835 | app.db.query(`UPDATE app SET access = 'public' WHERE id = ?1`).run(record.id); | |
| 836 | try { | |
| 837 | const before = calls.length; | |
| 838 | looks.sweep(); | |
| 839 | await looks.idle(); | |
| 840 | const call = calls.slice(before).find((c) => c.out.endsWith("-thumb.png"))!; | |
| 841 | expect( | |
| 842 | readGrant(dataDir, new URL(call.url).searchParams.get("t") ?? "", { | |
| 843 | app: record, | |
| 844 | env: "production", | |
| 845 | })?.who, | |
| 846 | ).toBeUndefined(); | |
| 847 | expect(thumbRow(head)!.takenAs).toBe("nobody"); | |
| 848 | } finally { | |
| 849 | app.db.query(`UPDATE app SET access = 'private' WHERE id = ?1`).run(record.id); | |
| 850 | } | |
| 851 | // And back: a stranger's view of the inside does not outlive the change. | |
| 852 | looks.sweep(); | |
| 853 | await looks.idle(); | |
| 854 | expect(thumbRow(head)!.takenAs).toBe("owner"); | |
| 855 | }, 60_000); | |
| 856 | ||
| 719 | 857 | 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 () => { |
| 720 | 858 | // `hello` is a private app; its repository is made public here. |
| 721 | 859 | expect(record.access).toBe("private"); |
new above
offline