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

Move the accessors out of looks/service.ts (keepLook, lookUrl, memoryPressure) so it leaves the boot's static closure #17277

opened this

Merged 41h 17m ago, live in production

mason/forge:mason/17182-move-the-accessors-out-of-looks-service → main 0 commits fork 1 thread · 1 unresolved

  • Merged. mason/17182-move-the-accessors-out-of-looks-service was merged into main as 3bdad32.

Review

Sign in to review this change.
17 files changed +102 −92
src/actions/front.ts +1 −1
@@ -47,7 +47,7 @@ import {
4747 lookUrl,
4848 type Look,
4949 } from "../core/looks.ts";
50 import { keepLook } from "../looks/service.ts";
50 import { keepLook } from "../looks/keep.ts";
5151 import { retryAt } from "../looks/retries.ts";
5252 import { whyNoPicture } from "../looks/why.ts";
5353 import { canReadMany, getRepo, getReposByIds, type Repo } from "../core/repos.ts";
src/actions/journey_walk.ts +2 −2
@@ -24,7 +24,7 @@ import { oneShot } from "../crew/one_shot.ts";
2424 import { ownHost, localFor } from "../kernel/own_host.ts";
2525 import { err, ok, type Result } from "../kernel/result.ts";
2626 import { closeBrowsers, takeLook } from "../looks/capture.ts";
27 import { lookUrl } from "../looks/service.ts";
27 import { grantLookUrl } from "../looks/grant_url.ts";
2828
2929 /**
3030 * What a visit to the app brings back: the page's text and where its picture is (or "" if none).
@@ -90,7 +90,7 @@ export async function visitApp(app: App, repo: Repo, out: string): Promise<Resul
9090 const { dataDir } = app.config;
9191 const host = runtime.hostFor(record.slug, "production");
9292 const token = signGrant(dataDir, { app: record, env: "production" }, GRANT_TTL_MS, Date.now(), { id: owner.id, name: owner.username, role: "admin" });
93 const url = lookUrl(dataDir, host, local.port, token, "/");
93 const url = grantLookUrl(dataDir, host, local.port, token, "/");
9494 // The text: through the grant door by hand, then the page with the cookie it set.
9595 let text = "";
9696 try {
src/looks/explore_pictures.ts +1 −1
@@ -8,7 +8,7 @@ import type { Database } from "bun:sqlite";
88 import { existsSync } from "node:fs";
99 import { join } from "node:path";
1010 import { DEFAULT_THEME, lookUrl, type Look, type LookKind } from "../core/looks.ts";
11 import { keepLook } from "./service.ts";
11 import { keepLook } from "./keep.ts";
1212
1313 interface Found {
1414 readonly repo_id: string;
src/looks/grant_url.ts added +19
@@ -0,0 +1,19 @@
1 /** The URL the look's browser opens: the app's grant door on the forge's plain-http listener. */
2
3 import { plainProof } from "../apps/grants.ts";
4
5 /**
6 * What the browser opens: the app's grant door on the forge's own plain-http
7 * listener. The `plain` proof tells the door this is that browser, which
8 * would drop a `Secure` cookie on http, so a forge whose public address is
9 * https still hands it a cookie it keeps (#11519).
10 */
11 export function grantLookUrl(
12 dataDir: string,
13 host: string,
14 port: string,
15 token: string,
16 page: string,
17 ): string {
18 return `http://${host}:${port}/__forge/grant?t=${encodeURIComponent(token)}&plain=${plainProof(dataDir, token)}&to=${encodeURIComponent(page)}`;
19 }
src/looks/keep.ts added +31
@@ -0,0 +1,31 @@
1 /** Whether a picture on record is one to keep (its row and its file on disk). */
2
3 import { closeSync, openSync, readSync } from "node:fs";
4 import { join } from "node:path";
5 import { LEGACY_THUMB_WIDTH, type Look } from "../core/looks.ts";
6 import { pngHeader } from "../design/image/png.ts";
7
8 /**
9 * Whether a picture on record is one to keep. Every one is, except a
10 * thumb from before thumbs were the page reduced (`LEGACY_THUMB_WIDTH`):
11 * that one is retaken, and shown until it is.
12 */
13 export function keepLook(dataDir: string, look: Look, staleBefore?: number): boolean {
14 if (look.error !== null) return false;
15 if (look.kind !== "thumb") return true;
16 // A thumb older than the cut is one to retake; it is still shown until the retake lands.
17 if (staleBefore !== undefined && Date.parse(look.createdAt) < staleBefore) return false;
18 let fd: number | undefined;
19 try {
20 fd = openSync(join(dataDir, look.path), "r");
21 const head = new Uint8Array(33);
22 readSync(fd, head, 0, 33, 0);
23 const parsed = pngHeader(head);
24 return !parsed.ok || parsed.value.width !== LEGACY_THUMB_WIDTH;
25 } catch {
26 // No file behind the row: nothing to show, so nothing to keep.
27 return false;
28 } finally {
29 if (fd !== undefined) closeSync(fd);
30 }
31 }
src/looks/memory_pressure.ts added +21
@@ -0,0 +1,21 @@
1 /** The share of a container's memory limit in use, from cgroup v2 file contents. */
2
3 /**
4 * The share of the limit the container truly holds. `memory.current`
5 * counts the page cache too — every git object and database page read
6 * lately, which the kernel hands back the moment anyone needs it — and a
7 * forge that reads its repositories all day sits above any ceiling by that
8 * number for good. The anonymous pages are what would have to give.
9 */
10 export function memoryPressure(
11 stat: string,
12 max: string,
13 current: string,
14 ): number | undefined {
15 if (max.trim() === "max") return undefined;
16 const limit = Number(max);
17 if (!(limit > 0)) return undefined;
18 const anon = /^anon (\d+)$/m.exec(stat);
19 const used = anon === null ? Number(current) : Number(anon[1]);
20 return Number.isFinite(used) ? used / limit : undefined;
21 }
src/looks/readable.ts +1 −1
@@ -13,7 +13,7 @@ import { canEnterApp, canSeeOwnerFacts, type Repo } from "../core/repos.ts";
1313 import { sealedPreview } from "../core/sealed.ts";
1414 import type { User } from "../core/users.ts";
1515 import { pairCounts, pairsLine } from "./pairs.ts";
16 import { keepLook } from "./service.ts";
16 import { keepLook } from "./keep.ts";
1717
1818 /**
1919 * Who may fetch a picture (#727, #738). Writers, all of them. Anyone else
src/looks/service.ts +6 −74
@@ -25,20 +25,17 @@
2525
2626 import { sealedPreview } from "../core/sealed.ts";
2727 import {
28 closeSync,
2928 existsSync,
3029 mkdirSync,
31 openSync,
3230 readdirSync,
3331 readFileSync,
34 readSync,
3532 renameSync,
3633 rmSync,
3734 } from "node:fs";
3835 import { dirname, join } from "node:path";
3936 import type { App } from "../app.ts";
4037 import { envBuild, envPull, isEnvName, previewEnv, type EnvName } from "../apps/data.ts";
41 import { plainProof, signGrant, type GrantWho } from "../apps/grants.ts";
38 import { signGrant, type GrantWho } from "../apps/grants.ts";
4239 import { appsRuntime } from "../apps/runtime_registry.ts";
4340 import {
4441 getAppById,
@@ -51,7 +48,6 @@ import {
5148 deleteLooks,
5249 deleteStrangerThumbs,
5350 DEFAULT_PAGE,
54 LEGACY_THUMB_WIDTH,
5551 DARK_KINDS,
5652 DEFAULT_THEME,
5753 kindsOfPage,
@@ -64,7 +60,6 @@ import {
6460 getLook,
6561 looksForEnv,
6662 recordLook,
67 type Look,
6863 type LookKind,
6964 } from "../core/looks.ts";
7065 import { crewHoldsCore, forgeCpus } from "../core/one_core.ts";
@@ -74,10 +69,13 @@ import { frontPicks } from "../core/front.ts";
7469 import { getRepoById } from "../core/repos.ts";
7570 import { getUserById } from "../core/users.ts";
7671 import { ownerLooksFor, PREVIEW_EVERYDAY, PREVIEW_NEWCOMER } from "../spawn/preview-looks.ts";
77 import { pngHeader } from "../design/image/png.ts";
7872 import { createLog } from "../kernel/log.ts";
7973 import { addCommitLook } from "../checks/looks.ts";
8074 import type { LookVitals } from "../checks/summary.ts";
75 import { NOT_SERVING } from "./why.ts";
76 import { grantLookUrl } from "./grant_url.ts";
77 import { keepLook } from "./keep.ts";
78 import { memoryPressure } from "./memory_pressure.ts";
8179 import { blobKey, deleteLooksAndObjects, deleteObjects } from "./archive.ts";
8280 import { keepAsMain } from "./main_looks.ts";
8381 import { closeBrowsers, findChromium, isNoBrowser, lookLanes, takeLook, type Capture } from "./capture.ts";
@@ -121,11 +119,6 @@ export interface LooksOptions {
121119 readonly maxWaitMs?: number | undefined;
122120 }
123121
124 /**
125 * What a look records when the app answers, but with a missing page or a
126 * server error: not serving.
127 */
128 export const NOT_SERVING = "not serving";
129122
130123 /**
131124 * The app serves when its page comes back with anything but a 404 or a
@@ -164,26 +157,6 @@ export function cgroupMemoryPressure(): number | undefined {
164157 }
165158 }
166159
167 /**
168 * The share of the limit the container truly holds. `memory.current`
169 * counts the page cache too — every git object and database page read
170 * lately, which the kernel hands back the moment anyone needs it — and a
171 * forge that reads its repositories all day sits above any ceiling by that
172 * number for good. The anonymous pages are what would have to give.
173 */
174 export function memoryPressure(
175 stat: string,
176 max: string,
177 current: string,
178 ): number | undefined {
179 if (max.trim() === "max") return undefined;
180 const limit = Number(max);
181 if (!(limit > 0)) return undefined;
182 const anon = /^anon (\d+)$/m.exec(stat);
183 const used = anon === null ? Number(current) : Number(anon[1]);
184 return Number.isFinite(used) ? used / limit : undefined;
185 }
186
187160 /** Above this share of the limit, a look waits. */
188161 const PRESSURE_CEILING = 0.7;
189162
@@ -252,31 +225,6 @@ export const lookPath = (
252225 ): string =>
253226 join("looks", appId, env, `${commitOid}-${lookSlot(page, kind, theme)}.png`);
254227
255 /**
256 * Whether a picture on record is one to keep. Every one is, except a
257 * thumb from before thumbs were the page reduced (`LEGACY_THUMB_WIDTH`):
258 * that one is retaken, and shown until it is.
259 */
260 export function keepLook(dataDir: string, look: Look, staleBefore?: number): boolean {
261 if (look.error !== null) return false;
262 if (look.kind !== "thumb") return true;
263 // A thumb older than the cut is one to retake; it is still shown until the retake lands.
264 if (staleBefore !== undefined && Date.parse(look.createdAt) < staleBefore) return false;
265 let fd: number | undefined;
266 try {
267 fd = openSync(join(dataDir, look.path), "r");
268 const head = new Uint8Array(33);
269 readSync(fd, head, 0, 33, 0);
270 const parsed = pngHeader(head);
271 return !parsed.ok || parsed.value.width !== LEGACY_THUMB_WIDTH;
272 } catch {
273 // No file behind the row: nothing to show, so nothing to keep.
274 return false;
275 } finally {
276 if (fd !== undefined) closeSync(fd);
277 }
278 }
279
280228 interface Pending {
281229 readonly appId: string;
282230 readonly env: EnvName;
@@ -288,22 +236,6 @@ interface Pending {
288236 readonly again?: true;
289237 }
290238
291 /**
292 * What the browser opens: the app's grant door on the forge's own plain-http
293 * listener. The `plain` proof tells the door this is that browser, which
294 * would drop a `Secure` cookie on http, so a forge whose public address is
295 * https still hands it a cookie it keeps (#11519).
296 */
297 export function lookUrl(
298 dataDir: string,
299 host: string,
300 port: string,
301 token: string,
302 page: string,
303 ): string {
304 return `http://${host}:${port}/__forge/grant?t=${encodeURIComponent(token)}&plain=${plainProof(dataDir, token)}&to=${encodeURIComponent(page)}`;
305 }
306
307239 export function startLooks(app: App, options: LooksOptions): LooksHandle {
308240 const { dataDir } = app.config;
309241 const port = new URL(options.localUrl).port;
@@ -682,7 +614,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
682614 Date.now(),
683615 asNobody(kind, page) ? undefined : isNewcomerLook(page) ? newcomer : isEverydayLook(page) ? everyday : asOwner,
684616 );
685 const url = lookUrl(dataDir, host, port, token, page);
617 const url = grantLookUrl(dataDir, host, port, token, page);
686618 const path = lookPath(item.appId, item.env, item.commitOid, page, kind, theme);
687619 const out = join(dataDir, path);
688620 // Taken to one side and moved in whole. A pull that closes while its
src/looks/why.ts +6 −1
@@ -6,7 +6,12 @@
66 */
77
88 import type { EnvState } from "../apps/runtime.ts";
9 import { NOT_SERVING } from "./service.ts";
9
10 /**
11 * What a look records when the app answers, but with a missing page or a
12 * server error: not serving.
13 */
14 export const NOT_SERVING = "not serving";
1015
1116 export interface NoPicture {
1217 /** Whether this viewer may be shown the app's pictures (`mayFetchLook`; a public app's: yes). */
src/runs/memory_hold.ts +1 −1
@@ -14,7 +14,7 @@
1414
1515 import { readFileSync } from "node:fs";
1616 import { join } from "node:path";
17 import { memoryPressure } from "../looks/service.ts";
17 import { memoryPressure } from "../looks/memory_pressure.ts";
1818 import { isSize } from "../spawn/sizes.ts";
1919 import { CGROUP_DIR_ENV, SIZE_ENV } from "../spawn/usage.ts";
2020
src/web/og/looks.ts +1 −1
@@ -11,7 +11,7 @@ import { previewEnv } from "../../apps/data.ts";
1111 import type { AppRecord } from "../../core/apps.ts";
1212 import { DEFAULT_PAGE, looksForEnv, lookVersion, type Look } from "../../core/looks.ts";
1313 import { sealedPreview } from "../../core/sealed.ts";
14 import { keepLook } from "../../looks/service.ts";
14 import { keepLook } from "../../looks/keep.ts";
1515 import type { App } from "../../app.ts";
1616 import type { CardImage, CardInput } from "./card.ts";
1717 import { shotUri } from "./shot.ts";
test/boot-lazy.test.ts +3 −2
@@ -24,11 +24,12 @@ test("the terminal's server is imported dynamically by the boot", () => {
2424 // #17021: the services only the boot starts are not in its static closure; that each still starts
2525 // is proved on a real boot (boot-production.test.ts, "background service started service=<name>").
2626 // The heavier ones are still reached by pages and actions, each its own follow-up: #17180,
27 // #17181, #17182, #17183 (checks/service, crew/dispatch, looks/service).
27 // #17181, #17183 (checks/service, crew/dispatch).
28 // looks/service is out (#17182): its accessors live in looks/keep.ts, grant_url.ts and memory_pressure.ts.
2829 // apps/runtime is out (#17179): its accessors live in apps/runtime_registry.ts.
2930 test("the boot's static imports do not reach the services only it starts", () => {
3031 const closure = [...staticClosure(resolve("src/main.ts"))];
31 const only = ["maintain/runner.ts", "nightly/service.ts", "keeper/keeper.ts", "keeper/wire.ts", "crew/routines.ts", "checks/service.ts", "snapshot/service.ts", "apps/runtime.ts"];
32 const only = ["maintain/runner.ts", "nightly/service.ts", "keeper/keeper.ts", "keeper/wire.ts", "crew/routines.ts", "checks/service.ts", "snapshot/service.ts", "apps/runtime.ts", "looks/service.ts"];
3233 for (const file of only) expect(closure.some((f) => f.endsWith(`/src/${file}`)), file).toBe(false);
3334 });
3435
test/front.test.ts +1 −1
@@ -15,7 +15,7 @@ import { lookNow } from "../src/web/pages/looks.ts";
1515 import type { Ctx } from "../src/http/context.ts";
1616 import { suspendAccount } from "../src/actions/accounts.ts";
1717 import { forgetFrontScores, frontPage } from "../src/actions/front.ts";
18 import * as lookService from "../src/looks/service.ts";
18 import * as lookService from "../src/looks/keep.ts";

The alias lookService now names keep.ts. Rename it (for example keep) so the spy at the spyOn(lookService, "keepLook") call reads true.

1919 import { openIssue } from "../src/actions/issues.ts";
2020 import { createRepo } from "../src/actions/repos.ts";
2121 import { changeSignup } from "../src/actions/signup.ts";
test/look-none.test.ts +1 −2
@@ -4,8 +4,7 @@ import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { clearRetry, noteRetry, retryAt } from "../src/looks/retries.ts";
7 import { NOT_SERVING } from "../src/looks/service.ts";
8 import { whyNoPicture } from "../src/looks/why.ts";
7 import { NOT_SERVING, whyNoPicture } from "../src/looks/why.ts";
98 import { noPicture } from "../src/web/look_none.ts";
109
1110 const dir = mkdtempSync(join(tmpdir(), "look-none-"));
test/look-probe.test.ts +2 −1
@@ -1,5 +1,6 @@
11 import { afterAll, expect, test } from "bun:test";
2 import { appAnswers, NOT_SERVING } from "../src/looks/service.ts";
2 import { appAnswers } from "../src/looks/service.ts";
3 import { NOT_SERVING } from "../src/looks/why.ts";
34 import { lookFlags } from "../src/looks/capture.ts";
45
56 const server = Bun.serve({
test/look-secure-grant.test.ts +1 −1
@@ -16,7 +16,7 @@ import { signGrant } from "../src/apps/proxy.ts";
1616 import { newApp } from "../src/actions/apps.ts";
1717 import { createUser } from "../src/core/users.ts";
1818 import { serve } from "../src/http/server.ts";
19 import { lookUrl } from "../src/looks/service.ts";
19 import { grantLookUrl as lookUrl } from "../src/looks/grant_url.ts";
2020 import { refusal } from "../src/looks/capture.ts";
2121 import { quietLogs } from "./helpers/globals.ts";
2222
test/looks.test.ts +4 −3
@@ -44,7 +44,8 @@ import {
4444 type Capture,
4545 type LookInput,
4646 } from "../src/looks/capture.ts";
47 import { NOT_ANSWERING, NOT_SERVING, startLooks, type LooksHandle } from "../src/looks/service.ts";
47 import { NOT_ANSWERING, startLooks, type LooksHandle } from "../src/looks/service.ts";
48 import { NOT_SERVING } from "../src/looks/why.ts";
4849 import type { BackoffClock } from "../src/looks/backoff.ts";
4950 import { logLevel, setLogLevel } from "../src/kernel/log.ts";
5051
@@ -1584,8 +1585,8 @@ describe("the look", () => {
15841585 });
15851586
15861587 test("memory pressure is what the container truly holds, never its page cache", async () => {
1587 const { cgroupMemoryPressure, memoryPressure } =
1588 await import("../src/looks/service.ts");
1588 const { cgroupMemoryPressure } = await import("../src/looks/service.ts");
1589 const { memoryPressure } = await import("../src/looks/memory_pressure.ts");
15891590 // Not a container here: unknown pressure is no pressure.
15901591 expect(
15911592 cgroupMemoryPressure() === undefined || cgroupMemoryPressure()! >= 0,

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

Keyboard shortcuts

Docs