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

GET /api/v1/changelog answers from a held reading, not a cold walk (first call 2.1 s on production, then 0.26 s) #15668

Merged opened this

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

Merged

scout/forge:scout/15631-get-api-v1-changelog-answers-from-a-held → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/15631-get-api-v1-changelog-answers-from-a-held was merged into main as f951822.

Review

Sign in to review this change.
8 files changed +162 −4
AGENTS.md +1
@@ -89,3 +89,4 @@ An app token's requests go behind people's and repeat reads are 304s (`src/http/
8989 A pull that changes code under `src/` adds or edits a `test/*.test.ts` too, or says `No test: <why>` in a commit line; `bun scripts/gate.ts` refuses it otherwise ("a behaviour a pull adds has a test that fails without it", #14235).
9090
9191 A pull that adds a page (`src/web/pages/*.ts`), an MCP tool (`src/http/mcp/tools/*.ts`) or a settings module (`src/settings/*.ts`) has a commit line `Replaces: <what it takes the place of>` or `Replaces: nothing, <why>` (#14249, `src/kernel/replaces.ts`); `bun scripts/gate.ts` says it as a note, never a refusal, and the reviewer holds the pull to that line.
92 `src/release/shipped_held.ts`: `heldShipped`, per forge, the public changelog answer (`shippedHeld`, which `GET /api/v1/changelog` answers from; the page, feeds and MCP walk fresh) held 60 s per `?repo=` value (20 at most) so the first call and the second share one git walk (#15631); `recordRelease`, `recordAppRelease` and `setReleaseTests` drop it (`forgetShipped`) so a release is never served stale; a walk that fails is not held; the route names the phase `shipped` in `server-timing` (`desc="hit"` when held); gone on restart.
src/apps/release_record.ts +8 −2
@@ -7,6 +7,7 @@
77 import type { Database } from "bun:sqlite";
88 import { readFileAt } from "./checkout.ts";
99 import { commitLog } from "../git/read.ts";
10 import { forgetShipped } from "../release/shipped_held.ts";
1011 import { parseVersion, recordAppRelease, setReleaseTests, type AppRelease } from "../core/app_releases.ts";
1112
1213 const ASK_MS = 2_000;
@@ -77,7 +78,7 @@ export async function noteRelease(
7778 if (version === undefined) return undefined;
7879 const log = await commitLog(input.repoDir, input.oid, { limit: 1 });
7980 const commit = log.ok ? log.value[0] : undefined;
80 return recordAppRelease(db, {
81 const recorded = recordAppRelease(db, {
8182 repoId: input.repoId,
8283 version,
8384 commit: input.oid,
@@ -87,6 +88,8 @@ export async function noteRelease(
8788 servingMs: between(input.pushedAt ?? input.startedAt, input.servingAt),
8889 servedAt: input.servingAt,
8990 });
91 if (recorded !== undefined) forgetShipped(db);
92 return recorded;
9093 }
9194
9295 /** Only production, with a declared `app.version`, records releases. */
@@ -103,5 +106,8 @@ export function noteReleaseTests(
103106 oid: string,
104107 passed: boolean,
105108 ): void {
106 if (recordsReleases(env, manifest) && manifest.test !== null) setReleaseTests(db, repoId, oid, passed ? "passed" : "failed");
109 if (recordsReleases(env, manifest) && manifest.test !== null) {
110 setReleaseTests(db, repoId, oid, passed ? "passed" : "failed");
111 forgetShipped(db);
112 }
107113 }
src/release/answer.ts +9
@@ -18,6 +18,10 @@ import { keeperReleaseOfSha, type Stage } from "../keeper/record.ts";
1818 import { listReleases, releaseName } from "./record.ts";
1919 import { mergeReleases, publicTagReleases } from "./repo_tags.ts";
2020 import { runningCheck } from "./running_check.ts";
21 import { heldShipped } from "./shipped_held.ts";
22
23 /** What the shipped walk answers. */
24 export type ShippedAnswer = Awaited<ReturnType<typeof shippedAnswer>>;
2125
2226 /**
2327 * What the forge can say of a kept release's soundness: the keeper's verdict, else the preflight's.
@@ -124,3 +128,8 @@ export function releasesAnswer(app: App, user: User | undefined): ReleasesAnswer
124128 },
125129 };
126130 }
131
132 /** The same answer from the held reading, and whether it was held (#15631): the public API's. */
133 export function shippedHeld(app: App, asked: string | null = null) {
134 return heldShipped(app.db, asked ?? "\u0000", () => shippedAnswer(app, asked));
135 }
src/release/landings.ts +3
@@ -20,6 +20,7 @@ import { runGit } from "../git/env.ts";
2020 import { repoDir } from "../git/repos.ts";
2121 import { readTip } from "../git/tip.ts";
2222 import { running } from "../kernel/version.ts";
23 import { forgetShipped } from "./shipped_held.ts";
2324 import { creditOf, type Credit } from "./credits.ts";
2425
2526 export interface Landing {
@@ -212,11 +213,13 @@ const keeps = new WeakMap<Database, LiveState>();
212213
213214 /** Keep what the running commit contains; a test says it directly. */
214215 export function keepLive(db: Database, own: string, oids: Iterable<string>, at: number, gap?: { commit: string; head: string; ahead: number }): void {
216 forgetShipped(db);

keepLive drops the hold. If a walk calls it after an await, it clears its own entry and the next call walks again. Needs a test.

215217 keeps.set(db, { own, oids: new Set(oids), misses: new Set(), at, commit: gap?.commit ?? "", ...(gap === undefined ? {} : { head: gap.head, ahead: gap.ahead }) });
216218 }
217219
218220 /** Forget it, so the alarm is silent until the next read. */
219221 export function forgetLive(db: Database): void {
222 forgetShipped(db);
220223 keeps.delete(db);
221224 deep.delete(db);
222225 founds.delete(db);
src/release/record.ts +2
@@ -1,6 +1,7 @@
11 /** The release rows: one per checked-out landing, with the preflight verdict. */
22
33 import type { Database } from "bun:sqlite";
4 import { forgetShipped } from "./shipped_held.ts";
45
56 export interface Release {
67 readonly id: number;
@@ -42,6 +43,7 @@ export function recordRelease(
4243 VALUES (?1, ?2, ?3, ?4, ?5, strftime('%Y-%m-%dT%H:%M:%fZ','now')) RETURNING *`,
4344 )
4445 .get(input.sha, input.repoId, input.pullNumber, input.ok ? 1 : 0, input.line)!;
46 forgetShipped(db);
4547 return toRelease(row);
4648 }
4749
src/release/shipped_held.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * The public changelog answer, held (#15631): the first call walks git and the release record,
3 * the next ones within `HELD_MS` share that one walk. One per forge (its database); a release
4 * landing drops it (the callers that record one), so a new version is never served stale.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import type { ShippedAnswer } from "./answer.ts";
9
10 export const HELD_MS = 60_000;
11 /** Distinct `?repo=` answers held per forge; a viewer chooses the key, so it is bounded. */
12 const MAX_KEYS = 20;
13
14 interface Held {
15 readonly at: number;
16 readonly answer: Promise<ShippedAnswer>;
17 }
18
outdated

Test-only counter in production code; count walks through the build callback in the test instead.

19 const held = new WeakMap<Database, Map<string, Held>>();
20
21 /**
22 * The held answer for `key`, or a new walk of `build` held for the next callers. A failed walk is
23 * not held; past `MAX_KEYS` the oldest key goes, so varying `?repo=` cannot push out a hot one.
24 */
25 export function heldShipped(db: Database, key: string, build: () => Promise<ShippedAnswer>, now = Date.now()): { answer: Promise<ShippedAnswer>; hit: boolean } {
26 let keep = held.get(db);
27 if (keep === undefined) held.set(db, (keep = new Map()));
28 const found = keep.get(key);
29 if (found !== undefined && now - found.at < HELD_MS) return { answer: found.answer, hit: true };
30 keep.delete(key);
31 if (keep.size >= MAX_KEYS) keep.delete(keep.keys().next().value!);
32 const answer = build();
33 const entry: Held = { at: now, answer };
outdated

clear() at 20 keys lets a varied ?repo= evict the hot key. Evict the oldest entry only.

34 keep.set(key, entry);
35 answer.catch(() => {
36 if (keep.get(key) === entry) keep.delete(key);
37 });
38 return { answer, hit: false };
39 }
40
41 /** A release landed: the next call walks again. */
42 export function forgetShipped(db: Database): void {
43 held.get(db)?.clear();
44 }
src/web/pages/changelog.ts +5 −2
@@ -33,7 +33,7 @@ import { changelogTag, holds } from "../feeds.ts";
3333 import { EDGE_FRESH, EDGE_STALE, EDGE_VARY } from "../../http/edge_cache.ts";
3434 import { json, securityFloor } from "../../http/respond.ts";
3535 import { readFlash } from "../flash.ts";
36 import { shippedAnswer } from "../../release/answer.ts";
36 import { shippedHeld } from "../../release/answer.ts";
3737 import { html, type Html } from "../html.ts";
3838 import { page } from "../layout.ts";
3939 import { badge, row, seg, sha, time, timeAgo } from "../ui.ts";
@@ -458,7 +458,10 @@ function cacheHeaders(ctx: Ctx, etag: string): { matched: boolean; response: Res
458458 export async function changelogJson(ctx: Ctx): Promise<Response> {
459459 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
460460 const asked = ctx.url.searchParams.get("repo");
461 const answer = await shippedAnswer(ctx.app, asked);
461 const began = performance.now();
462 const kept = shippedHeld(ctx.app, asked);
463 const answer = await kept.answer;
464 notePhase(ctx.request, "shipped", performance.now() - began, kept.hit);
462465 // The answer is the same for every viewer (public repositories only), so a shared cache may keep
463466 // it.
464467 const { releases } = answer;
test/changelog-held.test.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * GET /api/v1/changelog answers from a held reading: one walk for the first and second call,
3 * dropped when a release lands (#15631).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { forgetLive, keepLive } from "../src/release/landings.ts";
13 import type { ShippedAnswer } from "../src/release/answer.ts";
14 import { forgetShipped, heldShipped } from "../src/release/shipped_held.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20
21 beforeAll(async () => {
22 dataDir = await mkdtemp(join(tmpdir(), "forge-changelog-held-"));
23 app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge" });
24 servers = await serve(app);
25 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
26 if (!u.ok) throw new Error(u.error);
27 const made = await createRepo(app, u.value, { name: "forge", visibility: "public" });
28 if (!made.ok) throw new Error(String(made.error));
29
30 }, 30_000);
31
32 afterAll(async () => {
33 servers.stop();
34 app.close();
35 await rm(dataDir, { recursive: true, force: true });
36 });
37
38 const get = () => fetch(`${servers.url}/api/v1/changelog`);
39
40 const timing = async (): Promise<string> => {
41 const r = await get();
42 await r.json();
43 return r.headers.get("server-timing") ?? "";
44 };
45
46 test("the second call is held and names the phase", async () => {
47 forgetShipped(app.db);
48 expect(await timing()).toContain("shipped");
49 expect(await timing()).toMatch(/shipped;[^,]*desc="hit"/);
50 });
51
52 test("a release landing drops the held answer", async () => {
53 await timing();
54 expect(await timing()).toContain('desc="hit"');
55 forgetShipped(app.db);
56 expect(await timing()).not.toContain('desc="hit"');
57 });
58
59 const said = {} as ShippedAnswer;
60 const ok = () => Promise.resolve(said);
61
62 test("a held answer expires after 60 s and a failed walk is not held", async () => {
63 const t = 1_000_000;
64 expect(heldShipped(app.db, "k", ok, t).hit).toBe(false);
65 expect(heldShipped(app.db, "k", ok, t + 59_000).hit).toBe(true);
66 expect(heldShipped(app.db, "k", ok, t + 61_000).hit).toBe(false);
67 const bad = heldShipped(app.db, "bad", () => Promise.reject(new Error("x")), t);
68 await bad.answer.catch(() => {});
69 expect(heldShipped(app.db, "bad", ok, t + 1).hit).toBe(false);
70 });
71
72 test("the live state changing (keepLive, forgetLive) drops the held answer", async () => {
73 const t = 2_000_000;
74 await heldShipped(app.db, "live", ok, t).answer;
75 expect(heldShipped(app.db, "live", ok, t + 1).hit).toBe(true);
76 keepLive(app.db, "own", [], t);
77 expect(heldShipped(app.db, "live", ok, t + 2).hit).toBe(false);
78 forgetLive(app.db);
79 expect(heldShipped(app.db, "live", ok, t + 3).hit).toBe(false);
80 });
81
82 test("varying the key cannot push the hot one out", () => {
83 const t = 3_000_000;
84 heldShipped(app.db, "hot", ok, t);
85 for (let i = 0; i < 40; i++) heldShipped(app.db, `v${i}`, ok, t + 1 + i);
86 expect(heldShipped(app.db, "hot", ok, t + 100).hit).toBe(false);
87 heldShipped(app.db, "hot2", ok, t + 200);
88 for (let i = 0; i < 5; i++) heldShipped(app.db, `w${i}`, ok, t + 201 + i);
89 expect(heldShipped(app.db, "hot2", ok, t + 300).hit).toBe(true);
90 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs