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

Defect on the v1.0.0 path: production's /api/v1/changelog still says check null on commit f16369b, which already contains the #15529 fix #15538

Merged opened this

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

Merged

scout/forge:scout/15537-defect-on-the-v1-0-0-path-production-s-a → main 0 commits fork

  • Merged. scout/15537-defect-on-the-v1-0-0-path-production-s-a was merged into main as 356be4e.

Review

Sign in to review this change.
8 files changed +248 −10
scripts/v1-probe.ts +6 −3
@@ -268,9 +268,11 @@ export async function probe(base: string, repo: string, fetcher: Fetcher = fetch
268268
269269 // 3. The stranger journey's last green release: the public answer states the running commit's
270270 // check (#15514); when it names another commit or none, the check API (which a stranger may not
271 // read) is asked.
271 // read) is asked. `unknown` (#15537) is a hosted forge whose host did not say: no verdict
272 // either, so it is asked the same way, and the line says the release could not tell.
272273 const stated = typeof shipped === "string" ? undefined : runningCheckOf(json(shipped));
273 const own = stated !== undefined && stated.commit === tagCommit && stated.state !== "none" ? stated : undefined;
274 const own = stated !== undefined && stated.commit === tagCommit && stated.state !== "none" && stated.state !== "unknown" ? stated : undefined;
275 const untold = stated !== undefined && stated.commit === tagCommit && stated.state === "unknown";
274276 const checkPath = own ? releasePath : tagCommit ? `${api}/commits/${tagCommit}/check` : releasePath;
275277 if (!read) say("stranger journey green on a release", "UNKNOWN", checkPath, `${unread}; a person must open the latest release's check`);
276278 else if (!tagName || !tagCommit) say("stranger journey green on a release", "FAIL", checkPath, `the releases tool lists no release of ${repo} and names no running commit`);
@@ -278,7 +280,8 @@ export async function probe(base: string, repo: string, fetcher: Fetcher = fetch
278280 const check = own === undefined ? await get(checkPath) : undefined;
279281 const c = own ?? (check === undefined || typeof check === "string" ? undefined : (json(check) as { state?: unknown; runId?: unknown; finishedAt?: unknown } | undefined));
280282 if (!c || typeof c.state !== "string") {
281 const why = check === undefined ? "no check named" : typeof check === "string" ? check : `${check.status}, not the check's JSON`;
283 const asked = check === undefined ? "no check named" : typeof check === "string" ? check : `${check.status}, not the check's JSON`;
284 const why = untold ? `the release says its check is unknown (its host forge did not answer); ${asked}` : asked;
282285 // A 404 can mean the base holds no such repository, as on an app's test copy of the forge
283286 // (#15519): its own empty database states no verdict, however public the read, so the line
284287 // names the forge to ask in place of a person.
src/apps/process.ts +8
@@ -65,6 +65,8 @@ export interface StartInput {
6565 readonly url: string;
6666 readonly commitOid: string;
6767 readonly forgeUrl: string;
68 /** The repository the app runs, `owner/name`: whose check its commit's verdict is (#15537). */
69 readonly repo?: string | undefined;
6870 /** The key the app verifies `x-forge-identity` with (`apps/proxy.ts`). */
6971 readonly identityKey: string;
7072 /** The `ssh …` that opens this environment's terminal, when SSH is on. */
@@ -184,6 +186,8 @@ export function appEnv(input: {
184186 url: string;
185187 commitOid: string;
186188 forgeUrl: string;
189 /** `owner/name` of the repository the app runs, told as `FORGE_APP_REPO`. */
190 repo?: string | undefined;
187191 /** The key the app verifies `x-forge-identity` with. */
188192 identityKey: string;
189193 /** The exact `ssh …` that opens this environment's terminal, if any. */
@@ -216,6 +220,9 @@ export function appEnv(input: {
216220 FORGE_APP_DATA: input.dataDir,
217221 FORGE_APP_URL: input.url,
218222 FORGE_APP_COMMIT: input.commitOid,
223 // Which repository's check names this commit's verdict: a forge run as an app asks it
224 // (#15537).
225 ...(input.repo === undefined ? {} : { FORGE_APP_REPO: input.repo }),
219226 // A preview runs a pull, which is no release: only production is told one.
220227 ...(input.env === "production" && input.release !== undefined && /^\d+\.\d+\.\d+$/.test(input.release)
221228 ? { FORGE_APP_RELEASE: input.release }
@@ -733,6 +740,7 @@ export async function startProcess(
733740 url: input.url,
734741 commitOid: input.commitOid,
735742 forgeUrl: input.forgeUrl,
743 repo: input.repo,
736744 identityKey: input.identityKey,
737745 ssh: input.ssh,
738746 vars: input.vars,
src/apps/runtime_bringup.ts +1
@@ -122,6 +122,7 @@ export async function bringUp(
122122 commitOid: run.commitOid,
123123 ...(state.env === "production" ? { release: await releaseAt(bare, run.commitOid) } : {}),
124124 forgeUrl: rt.options.forgeUrl,
125 repo: `${repo.ownerName}/${repo.name}`,
125126 identityKey: identityKey(rt.app.config.dataDir, state.app.id),
126127 ssh: rt.sshFor(state.app, state.env),
127128 // Read at start, never cached: a change is a redeploy, and the
src/apps/runtime_sleep.ts +1
@@ -171,6 +171,7 @@ export async function wake(rt: AppsRuntime, record: AppRecord, env: EnvName): Pr
171171 url: rt.urlFor(record, env),
172172 commitOid: asleep.commitOid,
173173 forgeUrl: rt.options.forgeUrl,
174 repo: `${repo.ownerName}/${repo.name}`,
174175 identityKey: identityKey(rt.app.config.dataDir, record.id),
175176 ssh: rt.sshFor(record, env),
176177 ...rt.secretsFor(repo, record.id, env, token.token, asleep.dir),
src/release/host_check.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * The running commit's check, asked of the host forge (#15537). A forge run as an app of another
3 * keeps its own empty database: its `FORGE_REPO` is unset and its runs are not here, so the
4 * verdict on the commit it runs lives only on the host, which ran the check. The host tells the
5 * app its repository (`FORGE_APP_REPO`), its API (`FORGE_API_URL`) and a read-only token
6 * (`FORGE_TOKEN`); this asks `GET …/repos/<repo>/commits/<commit>/check` with them, and keeps
7 * only the state and the run id of the answer.
8 */
9
10 import type { CommitCheckState } from "../checks/commit_check.ts";
11
12 type Env = Record<string, string | undefined>;
13
14 /** What of the host's answer is kept: never its summary, log or looks. */
15 export interface HostVerdict {
16 readonly state: CommitCheckState;
17 readonly runId: string | null;
18 }
19
20 /** How long the host is waited for before the answer says `unknown`. */
21 export const HOST_WAIT_MS = 2_000;
22
23 const STATES: readonly string[] = ["ok", "failed", "pending", "superseded", "none"];
24 const REPO = /^[A-Za-z0-9._-]{1,80}\/[A-Za-z0-9._-]{1,80}$/;
25
26 /** Where to ask, or undefined when this forge is not an app of a host that told it enough. */
27 export function hostCheckUrl(env: Env, commit: string): { url: string; token: string } | undefined {
28 const repo = (env["FORGE_APP_REPO"] ?? "").trim();
29 const api = (env["FORGE_API_URL"] ?? "").trim().replace(/\/+$/, "");
30 const token = (env["FORGE_TOKEN"] ?? "").trim();
31 if (!REPO.test(repo) || repo.split("/").some((part) => /^\.+$/.test(part)) || !/^https?:\/\/[^/\s]+/.test(api) || token === "") return undefined;
32 if (!/^[0-9a-f]{40}$/.test(commit)) return undefined;
33 const [owner = "", name = ""] = repo.split("/");
34 return { url: `${api}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/commits/${commit}/check`, token };
35 }
36
37 /** The host's state and run id from its JSON answer, or undefined when it is not one. */
38 export function verdictOf(body: unknown): HostVerdict | undefined {
39 if (body === null || typeof body !== "object") return undefined;
40 const { state, runId } = body as { state?: unknown; runId?: unknown };
41 if (typeof state !== "string" || !STATES.includes(state)) return undefined;
42 const id = typeof runId === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(runId) ? runId : null;
43 return { state: state as CommitCheckState, runId: id };
44 }
45
46 /**
47 * The host's verdict on `commit`, or undefined when there is no host to ask, it does not answer
48 * in time, or answers anything but the check's JSON.
49 */
50 export async function hostCheck(
51 env: Env,
52 commit: string,
53 fetcher: (url: string, init: RequestInit) => Promise<Response> = fetch,
54 ): Promise<HostVerdict | undefined> {
55 const asked = hostCheckUrl(env, commit);
56 if (asked === undefined) return undefined;
57 try {
58 const response = await fetcher(asked.url, {
59 headers: { authorization: `Bearer ${asked.token}`, accept: "application/json" },
60 signal: AbortSignal.timeout(HOST_WAIT_MS),
61 redirect: "error",
62 });
63 if (!response.ok) return undefined;
64 return verdictOf(await response.json());
65 } catch {
66 return undefined;
67 }
68 }
src/release/running_check.ts +43 −7
@@ -4,6 +4,10 @@
44 * stranger can see the release's tests ran green without reading the runs. Only the running
55 * commit of the forge's own repository (`FORGE_REPO`) is ever asked, and only its state and run id
66 * leave: no summary, no log, no other commit's check.
7 *
8 * A forge run as an app of another (#15537) holds neither that repository nor its runs: the host
9 * ran the check, so the host is asked (`host_check.ts`). When no verdict can be had, the answer
10 * says `unknown` rather than null, so a reader can tell "not known here" from "never checked".
711 */
812
913 import type { App } from "../app.ts";
@@ -11,9 +15,13 @@ import { releaseCheck, type CommitCheck } from "../checks/commit_check.ts";
1115 import { forgeRepo } from "../core/forge_repo.ts";
1216 import { hasCommit, isAncestor } from "../git/builds.ts";
1317 import { repoDir } from "../git/repos.ts";
18 import { hostCheck, type HostVerdict } from "./host_check.ts";
1419
15 /** `running` is queued or running; `none` is never checked, or every check of it was cancelled. */
16 export type RunningCheckState = "ok" | "failed" | "running" | "none";
20 /**
21 * `running` is queued or running; `none` is never checked, or every check of it was cancelled;
22 * `unknown` is that this forge holds no record of the check and its host did not say (#15537).
23 */
24 export type RunningCheckState = "ok" | "failed" | "running" | "none" | "unknown";
1725
1826 export interface RunningCheck {
1927 readonly commit: string;
@@ -32,16 +40,30 @@ export function runningState(state: CommitCheck["state"]): RunningCheckState {
3240 */
3341 const settled = new WeakMap<App["db"], RunningCheck>();
3442
43 /** How long an unsettled answer from the host is kept, so the changelog never waits on it twice. */
44 export const HOST_FRESH_MS = 60_000;
45 const asked = new WeakMap<App["db"], { answer: RunningCheck; at: number }>();
46
47 /** Asks the host forge for its verdict on a commit: `hostCheck` over this process's env. */
48 export type AskHost = (commit: string) => Promise<HostVerdict | undefined>;
49 const askHost: AskHost = (commit) => hostCheck(process.env, commit);
50
3551 /**
36 * The running commit's check, or null when the forge names no repository of its own or no commit.
52 * The running commit's check, or null when there is no running commit. Without a repository of its
53 * own here it is the host's (`ask`), and `unknown` when the host does not say.
3754 */
38 export async function runningCheck(app: App, commit: string | null): Promise<RunningCheck | null> {
55 export async function runningCheck(
56 app: App,
57 commit: string | null,
58 ask: AskHost = askHost,
59 now: () => number = Date.now,
60 ): Promise<RunningCheck | null> {
3961 if (commit === null || !/^[0-9a-f]{40}$/.test(commit)) return null;
40 // Private too (#15528): a release's verdict on its own public commit is the release's claim.
41 const repo = forgeRepo(app);
42 if (repo === undefined) return null;
4362 const kept = settled.get(app.db);
4463 if (kept !== undefined && kept.commit === commit) return kept;
64 // Private too (#15528): a release's verdict on its own public commit is the release's claim.
65 const repo = forgeRepo(app);
66 if (repo === undefined) return fromHost(app, commit, ask, now);
4567 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
4668 const found = await releaseCheck(app.db, repo.id, repo.defaultBranch, commit, {
4769 has: () => hasCommit(dir, commit),
@@ -51,3 +73,17 @@ export async function runningCheck(app: App, commit: string | null): Promise<Run
5173 if (answer.state === "ok" || answer.state === "failed") settled.set(app.db, answer);
5274 return answer;
5375 }
76
77 /** The host's verdict, kept for good once settled and for {@link HOST_FRESH_MS} otherwise. */
78 async function fromHost(app: App, commit: string, ask: AskHost, now: () => number): Promise<RunningCheck> {
79 const recent = asked.get(app.db);
80 if (recent !== undefined && recent.answer.commit === commit && now() - recent.at < HOST_FRESH_MS) return recent.answer;
81 const found = await ask(commit);
82 const answer: RunningCheck =
83 found === undefined
84 ? { commit, state: "unknown", runId: null }
85 : { commit, state: runningState(found.state), runId: found.runId };
86 if (answer.state === "ok" || answer.state === "failed") settled.set(app.db, answer);
87 else asked.set(app.db, { answer, at: now() });
88 return answer;
89 }
test/running-check-hosted.test.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * A forge run as an app of another (#15537): its own database holds no `FORGE_REPO` and none of
3 * its runs, which is why production's changelog said `check: null`. The verdict is the host's,
4 * asked with what the host hands the app; when it cannot be had, the answer says `unknown`.
5 */
6 import { afterAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { appEnv } from "../src/apps/process.ts";
12 import { hostCheck, hostCheckUrl, verdictOf } from "../src/release/host_check.ts";
13 import { HOST_FRESH_MS, runningCheck } from "../src/release/running_check.ts";
14 import { shippedAnswer } from "../src/release/answer.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 const OID = (c: string) => c.repeat(40);
20 const dirs: string[] = [];
21 const apps: App[] = [];
22
23 /** A hosted forge as production runs it: no FORGE_REPO, an empty database. */
24 async function hosted(): Promise<App> {
25 const dataDir = await mkdtemp(join(tmpdir(), "forge-hosted-check-"));
26 dirs.push(dataDir);
27 const made = createApp({ dataDir, port: 0 });
28 apps.push(made);
29 return made;
30 }
31
32 const HOST = { FORGE_APP_REPO: "trevato/forge", FORGE_API_URL: "https://forge.test/api/v1", FORGE_TOKEN: "ro-token" };
33
34 afterAll(async () => {
35 for (const a of apps) a.close();
36 for (const d of dirs) await rm(d, { recursive: true, force: true });
37 });
38
39 test("the host tells a production app which repository it runs", () => {
40 const env = appEnv({
41 port: 4321,
42 dataDir: "/data/x",
43 env: "production",
44 url: "http://lab.apps.test",
45 commitOid: OID("a"),
46 forgeUrl: "http://forge.test",
47 repo: "trevato/forge",
48 identityKey: "k",
49 });
50 expect(env["FORGE_APP_REPO"]).toBe("trevato/forge");
51 expect(env["FORGE_API_URL"]).toBe("http://forge.test/api/v1");
52 });
53
54 test("a hosted forge states the host's verdict on its running commit, in three fields only", async () => {
55 const app = await hosted();
56 const asked: string[] = [];
57 const found = await runningCheck(app, OID("b"), async (c) => {
58 asked.push(c);
59 return { state: "ok", runId: "run1" };
60 });
61 expect(found).toEqual({ commit: OID("b"), state: "ok", runId: "run1" });
62 expect(Object.keys(found ?? {}).sort()).toEqual(["commit", "runId", "state"]);
63 // Settled: never asked again.
64 await runningCheck(app, OID("b"), async () => { throw new Error("asked twice"); });
65 expect(asked).toEqual([OID("b")]);
66 });
67
68 test("with no host to ask, the answer is unknown, not null", async () => {
69 const app = await hosted();
70 expect(await runningCheck(app, OID("c"), async () => undefined)).toEqual({ commit: OID("c"), state: "unknown", runId: null });
71 const before = process.env["FORGE_COMMIT"];
72 process.env["FORGE_COMMIT"] = OID("c");
73 try {
74 // The public answer, as production gives it with no host variables: never `check: null`.
75 expect((await shippedAnswer(app)).check).toEqual({ commit: OID("c"), state: "unknown", runId: null });
76 } finally {
77 if (before === undefined) delete process.env["FORGE_COMMIT"];
78 else process.env["FORGE_COMMIT"] = before;
79 }
80 });
81
82 test("a running check is asked again once it is stale, and kept while fresh", async () => {
83 const app = await hosted();
84 let clock = 1_000;
85 let calls = 0;
86 const ask = async () => {
87 calls += 1;
88 return calls === 1 ? ({ state: "pending", runId: "r" } as const) : ({ state: "failed", runId: "r" } as const);
89 };
90 expect((await runningCheck(app, OID("d"), ask, () => clock))?.state).toBe("running");
91 expect((await runningCheck(app, OID("d"), ask, () => clock + 10))?.state).toBe("running");
92 expect(calls).toBe(1);
93 clock += HOST_FRESH_MS;
94 expect(await runningCheck(app, OID("d"), ask, () => clock)).toEqual({ commit: OID("d"), state: "failed", runId: "r" });
95 });
96
97 test("the host is asked at its check API with the token, and only state and run id are kept", async () => {
98 let seen: { url: string; auth: string | null } | undefined;
99 const fetcher = async (url: string, init: RequestInit) => {
100 seen = { url, auth: new Headers(init.headers).get("authorization") };
101 return Response.json({ state: "ok", runId: "abc_1", summary: "secret log", looks: [] });
102 };
103 expect(await hostCheck(HOST, OID("e"), fetcher)).toEqual({ state: "ok", runId: "abc_1" });
104 expect(seen).toEqual({ url: `https://forge.test/api/v1/repos/trevato/forge/commits/${OID("e")}/check`, auth: "Bearer ro-token" });
105 });
106
107 test("anything but the check's JSON, or a host that is not named, is no verdict", async () => {
108 expect(await hostCheck(HOST, OID("f"), async () => new Response("no", { status: 404 }))).toBeUndefined();
109 expect(await hostCheck(HOST, OID("f"), async () => { throw new Error("refused"); })).toBeUndefined();
110 expect(hostCheckUrl({ ...HOST, FORGE_APP_REPO: "../x" }, OID("f"))).toBeUndefined();
111 expect(hostCheckUrl({ ...HOST, FORGE_TOKEN: "" }, OID("f"))).toBeUndefined();
112 expect(hostCheckUrl(HOST, "nope")).toBeUndefined();
113 expect(verdictOf({ state: "great", runId: "x" })).toBeUndefined();
114 expect(verdictOf({ state: "ok", runId: "<script>" })).toEqual({ state: "ok", runId: null });
115 });
test/v1-probe.test.ts +6
@@ -233,6 +233,12 @@ describe("v1 probe", () => {
233233 expect(silent.verdict).toBe("UNKNOWN");
234234 expect(silent.evidence).toContain("a person must open v1.0.0's check");
235235 }
236 // A hosted forge whose host did not answer says `unknown` (#15537): the check API is asked,
237 // and the line says the release could not tell, not that its check is "unknown".
238 const untold = (await run({ checkState: null, stated: { commit: COMMIT, state: "unknown", runId: null } }))["stranger journey green on a release"]!;
239 expect(untold.verdict).toBe("UNKNOWN");
240 expect(untold.evidence).toContain("the release says its check is unknown (its host forge did not answer)");
241 expect(untold.evidence).toContain("a person must open v1.0.0's check");
236242 });
237243
238244 test("a base that holds no such repository says so and names the forge to ask, not a bare 404 (#15519)", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs