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

/api/v1/health names the release and the schedule count, so the v1 proof can read them #13268

Merged opened this

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

Merged

mason/forge:mason/13263-api-v1-health-names-the-release-and-the → main 5 commits fork 1 thread · 1 unresolved

  • Merged. mason/13263-api-v1-health-names-the-release-and-the was merged into main as 66c3760.

Review

Sign in to review this change.
8 files changed +99 −16
src/actions/health.ts +18 −4
@@ -38,6 +38,7 @@ import {
3838 import { snapshotsOf } from "../snapshot/service.ts";
3939 import { optionals, type Optional } from "../system/footprint.ts";
4040 import { forgesMemory, memoryOverLine } from "../spawn/memory_fit.ts";
41 import { releaseOf } from "../kernel/version.ts";
4142 import { forgeHasNoKey, NO_KEY_AT, NO_KEY_LINE } from "../crew/no_key.ts";
4243
4344 /** Where this forge's snapshots go, as vitals reads it; undefined when it takes none. */
@@ -120,13 +121,25 @@ export interface Parts {
120121 readonly optional: readonly Optional[];
121122 }
122123
123 /** The forge's overdue schedules as counts, on the health answer (#12512). */
124 /**
125 * The forge's schedules as counts, on the health answer: how many are overdue and by how long
126 * the worst (#12512), how many are not paused and how many of those have run (#13252).
127 */
124128 export interface ScheduleHealth {
125129 readonly schedules: ScheduleCounts;
126130 }
127131
128132 /**
129 * The health answer the API and MCP `health` give: `readHealth` plus the overdue schedules.
133 * The release that is running, `x.y.z`, or null when the build names none (#13263): what the
134 * v1 proof reads. `version` stays as it was for the release swap and the keeper.
135 */
136 export interface ReleaseHealth {
137 readonly release: string | null;
138 }
139
140 /**
141 * The health answer the API and MCP `health` give: `readHealth` plus the release and the
142 * schedules.
130143 * Only this answer pays for the schedule read; the asks, home and forge view that read
131144 * health for its standing do not (#12512).
132145 */
@@ -135,8 +148,9 @@ export function healthAnswer(
135148 actor: User | undefined,
136149 probe = false,
137150 now: number = Date.now(),
138 ): ReturnType<typeof readHealth> & ScheduleHealth {
139 return { ...readHealth(app, actor, probe), schedules: overdueSchedules(app.db, now) };
151 ): ReturnType<typeof readHealth> & ReleaseHealth & ScheduleHealth {
152 const schedules = overdueSchedules(app.db, now);
153 return { ...readHealth(app, actor, probe), release: releaseOf(), schedules };
140154 }
141155
142156 export function readHealth(
src/contract/openapi.ts +14 −4
@@ -16,7 +16,10 @@ import { OAUTH_SCOPES, type OAuthScope } from "../core/oauth.ts";
1616 import { tagList, tagOf } from "./tags.ts";
1717 import * as each from "./openapi/routes/index.ts";
1818
19 /** What each OAuth scope grants; a scope added to OAUTH_SCOPES without a line here fails the type check. */
19 /**
20 * What each OAuth scope grants; a scope added to OAUTH_SCOPES without a line here fails the type
21 * check.
22 */
2023 const SCOPE_WORDS: Readonly<Record<OAuthScope, string>> = {
2124 ro: "Read the API as the person",
2225 rw: "Read and write the API as the person",
@@ -32,7 +35,10 @@ export const oauthScopeFor = (method: Route["method"]): OAuthScope => (method ==
3235 /** Every row, sorted by operationId: the index's order. */
3336 export const ROUTES: readonly Route[] = Object.values(each);
3437
35 /** A GET that declares a `cursor` pages by it; `?page=` and `?offset=` are refused with a 400 (`http/cursor_lists.ts`). */
38 /**
39 * A GET that declares a `cursor` pages by it; `?page=` and `?offset=` are refused with a 400
40 * (`http/cursor_lists.ts`).
41 */
3642 export const pagesByCursor = (r: Pick<Route, "method" | "query">): boolean => r.method === "get" && r.query !== undefined && "cursor" in r.query;
3743
3844 const PAGE_REFUSAL = "page or offset was sent: this list pages by cursor, pass next_cursor as ?cursor= (400)";
@@ -42,10 +48,13 @@ export function operationId(r: Pick<Route, "method" | "path">): string {
4248 return `${r.method}${r.path.replace(/[^A-Za-z0-9]+(.)?/g, (_, c: string | undefined) => (c ?? "").toUpperCase())}`;
4349 }
4450
51 /** A field's schema; `"string|null"` is a nullable string, OpenAPI 3.1's type array (#13263). */
4552 const schema = (t: QueryType) =>
4653 typeof t !== "string"
4754 ? { type: t.type, ...(t.min === undefined ? {} : { minimum: t.min }), ...(t.max === undefined ? {} : { maximum: t.max }) }
48 : (t === "object" ? { type: "object" } : t === "array" ? { type: "array", items: { type: "object" } } : { type: t });
55 : t.includes("|")
56 ? { type: t.split("|") }
57 : (t === "object" ? { type: "object" } : t === "array" ? { type: "array", items: { type: "object" } } : { type: t });
4958
5059 /** The roles each role may act as: an admin is a member, a member is anonymous too. */
5160 const REACHES: Readonly<Record<Role, readonly Role[]>> = {
@@ -156,7 +165,8 @@ export function openapi(origin: string, version: string, role: Role): Record<str
156165 components: {
157166 securitySchemes: {
158167 token: { type: "http", scheme: "bearer" },
159 // RFC 6749 §4.1 authorization code (with PKCE), §6 refresh; the token endpoint serves both grants.
168 // RFC 6749 §4.1 authorization code (with PKCE), §6 refresh; the token endpoint serves both
169 // grants.
160170 oauth2: {
161171 type: "oauth2",
162172 flows: {
src/contract/openapi/routes/getApiV1Health.ts +2 −2
@@ -4,8 +4,8 @@ export const route: Route = {
44 method: "get",
55 path: "/api/v1/health",
66 summary:
7 "How the forge is, uncached; anyone may ask, a stranger is told little, the release probe and a site admin the whole of it. Every answer carries schedules {overdue, oldestSeconds, total, ran}: how many unpaused schedules are more than five minutes past due, the age in seconds of the most overdue (0 when none), how many unpaused schedules there are and how many of them have a recorded run, counts only, naming no app or repository",
7 "How the forge is, uncached; anyone may ask, a stranger is told little, the release probe and a site admin the whole of it. Every answer carries release, the running release as x.y.z or null when the build names none (version is unchanged and may say dev), and schedules {overdue, oldestSeconds, total, ran}: how many unpaused schedules are more than five minutes past due, the age in seconds of the most overdue (0 when none), how many unpaused schedules there are and how many of them have a recorded run, counts only, naming no app or repository",
88 auth: false,
99 role: "anonymous",
10 reply: { ok: "boolean", draining: "boolean", schedules: "object" },
10 reply: { ok: "boolean", draining: "boolean", release: "string|null", schedules: "object" },
outdated

The summary now names release, but reply still lists only ok, draining and schedules. Add release: "string|null" (or whatever form the contract uses for a nullable string) so the contract matches the answer.

1111 };
src/core/v1_proof.ts +7 −2
@@ -47,10 +47,15 @@ async function bodyOk(get: Get, path: string, status = 200): Promise<Got> {
4747 return got;
4848 }
4949
50 /** The release the forge runs, as `/api/v1/health` says it: `x.y.z`, or the probe fails. */
50 /**
51 * The release the forge runs, as `/api/v1/health` says it: `x.y.z`, or the probe fails. Its
52 * `release` field (#13263) when it has one, null on a build with none; a forge from before it
53 * is read by its `version`.
54 */
5155 async function release(get: Get): Promise<string> {
5256 const got = await bodyOk(get, "/api/v1/health");
53 const v = (JSON.parse(got.text) as { version?: unknown }).version;
57 const body = JSON.parse(got.text) as { version?: unknown; release?: unknown };
58 const v = "release" in body ? body.release : body.version;
5459 expect(typeof v === "string" && /^\d+\.\d+\.\d+$/.test(v), "/api/v1/health names no x.y.z release");
5560 return String(v);
5661 }
src/kernel/version.ts +11
@@ -52,3 +52,14 @@ export function runningLine(r: Running = running()): string {
5252 ? r.version
5353 : `${r.version} · ${r.commit.slice(0, 7)}`;
5454 }
55
56 const RELEASE = /^\d+\.\d+\.\d+$/;
57
58 /**
59 * The release that is running as `x.y.z`, or null when the build names none (#13263): a probe
60 * reads it as a version, so an unstamped forge's `dev`, or any stamp that is not a release
61 * number, is null here, never a word in a version's place.
62 */
63 export function releaseOf(r: Running = running()): string | null {
64 return RELEASE.test(r.version) ? r.version : null;
65 }
test/health-schedules.test.ts +33 −2
@@ -12,7 +12,9 @@ import { createApp as createAppRecord } from "../src/core/apps.ts";
1212 import { createRepo } from "../src/core/repos.ts";
1313 import { createUser } from "../src/core/users.ts";
1414 import { OVERDUE_AFTER_MS, overdueSchedules, recordRun, setPaused, scheduleTimer, syncSchedules } from "../src/core/timers.ts";
15 import { releaseOf, running, UNSTAMPED } from "../src/kernel/version.ts";
1516 import { serve, type Servers } from "../src/http/server.ts";
17 import { openapi } from "../src/contract/openapi.ts";
1618
1719 let dataDir: string;
1820 let app: App;
@@ -71,9 +73,10 @@ test("a schedule due inside the loop's slack is not overdue; one past it is, wit
7173 expect(read.oldestSeconds).toBe(Math.floor((now - due) / 1000));
7274
7375 const text = await strangerHealth();
74 const body = JSON.parse(text) as { schedules: { overdue: number; oldestSeconds: number } };
75 expect(Object.keys(body).sort()).toEqual(["commit", "draining", "ok", "schedules", "version"]);
76 const body = JSON.parse(text) as { schedules: { overdue: number; oldestSeconds: number; total: number } };
77 expect(Object.keys(body).sort()).toEqual(["commit", "draining", "ok", "release", "schedules", "version"]);
7678 expect(body.schedules.overdue).toBe(1);
79 expect(body.schedules.total).toBe(read.total);
7780 expect(body.schedules.oldestSeconds).toBeGreaterThanOrEqual(read.oldestSeconds);
7881 // Counts only: nothing names whose schedule it is.
7982 for (const word of ["secret-paper", "secret-nightly", "repo-of-secret-paper", "secret-owner", appId, "/jobs/run"]) expect(text).not.toContain(word);
@@ -83,8 +86,26 @@ test("a paused schedule is not overdue", async () => {
8386 const now = Date.now();
8487 const appId = await arm("paused-paper", "weekly", now - 7_200_000);
8588 const before = overdueSchedules(app.db, now).overdue;
89 const total = overdueSchedules(app.db, now).total;
8690 setPaused(app.db, scheduleTimer(app.db, appId, "weekly", "production")!.id, true, now);
8791 expect(overdueSchedules(app.db, now).overdue).toBe(before - 1);
92 expect(overdueSchedules(app.db, now).total).toBe(total - 1);
93 });
94
95 test("a build with no release says release null, and version is unchanged (#13263)", async () => {
96 const body = JSON.parse(await strangerHealth()) as { version: unknown; release: unknown };
97 // The test forge is built from no release: version keeps its word for the swap and the
98 // keeper, release says there is none rather than passing that word off as a version.
99 expect(body.version).toBe(running().version);
100 expect(body.version).toBe(UNSTAMPED);
101 expect(body.release).toBeNull();
102 });
103
104 test("release is x.y.z from the stamp, and null for any stamp that is not one", () => {
105 expect(releaseOf(running({ FORGE_VERSION: "v1.0.0" }))).toBe("1.0.0");
106 expect(releaseOf(running({ FORGE_VERSION: "0.7.604" }))).toBe("0.7.604");
107 expect(running({ FORGE_VERSION: "0.7.604" }).version).toBe("0.7.604");
108 for (const stamp of [undefined, "", "dev", "1.0", "1.0.0-rc1", "main"]) expect(releaseOf(running({ FORGE_VERSION: stamp }))).toBeNull();
88109 });
89110
90111 test("total counts unpaused schedules and ran those with a recorded run (#13252)", async () => {
@@ -103,3 +124,13 @@ test("total counts unpaused schedules and ran those with a recorded run (#13252)
103124 expect(body.schedules.total).toBe(armed.total);
104125 expect(body.schedules.ran).toBe(before.ran + 1);
105126 });
127
128 test("the contract declares release as a nullable string, and every reply key is served (#13263)", async () => {
129 const doc = openapi("https://f.test", "1", "anonymous") as {
130 paths: Record<string, { get: { responses: Record<string, { content: Record<string, { schema: { properties: Record<string, { type: unknown }> } }> }> } }>;
131 };
132 const props = doc.paths["/api/v1/health"]!.get.responses["200"]!.content["application/json"]!.schema.properties;
133 expect(props.release!.type).toEqual(["string", "null"]);
134 const body = JSON.parse(await strangerHealth()) as Record<string, unknown>;
135 for (const k of Object.keys(props)) expect(Object.keys(body)).toContain(k);
136 });
test/v1-proven.test.ts +12
@@ -73,6 +73,18 @@ describe("v1-proven", () => {
7373 expect(line(results.find((r) => r.issue === 13042)!)).toBe("fail #13042 the release production runs is 1.0.0 or later: the release is 0.7.604, not 1.0.0");
7474 });
7575
76 test("the release field is read over version when the forge has it, and null is no release (#13263)", async () => {
77 const said = (body: object) => stub({ "/api/v1/health": () => Response.json({ ok: true, commit: "058b6cf", draining: false, schedules: { overdue: 0, oldestSeconds: 0, total: 3, ran: 2 }, ...body }) });
78 const stamped = await prove("https://f.test", said({ version: "1.0.0", release: "1.0.0" }));
79 expect(line(stamped.find((r) => r.issue === 13042)!)).toBe("pass #13042 the release production runs is 1.0.0 or later: release 1.0.0 (1.0.0) is 1.0.0 or later");
80 expect(line(stamped.find((r) => r.issue === 11595)!)).toBe("pass #11595 no schedule is past its period: /api/v1/health: 3 schedule(s), 2 with a recorded run, none overdue");
81 // An unstamped build: version keeps its word, release says none, and the proof never reads
82 // the version in its place.
83 const unstamped = await prove("https://f.test", said({ version: "1.0.0", release: null }));
84 expect(line(unstamped.find((r) => r.issue === 10304)!)).toBe("fail #10304 production reports the release it runs: /api/v1/health names no x.y.z release");
85 expect(unstamped.find((r) => r.issue === 13042)!.status).toBe("fail");
86 });
87
7688 test("only reads: every request is a GET", async () => {
7789 const seen: string[] = [];
7890 await prove("https://f.test", stub({}, seen));
test/vitals.test.ts +2 −2
@@ -95,7 +95,7 @@ test("a site admin with a read-only token gets the shape; others get the short o
9595 [
9696 "accessLog",
9797 "apps", "at", "broken", "checkedAt", "commit", "degraded", "disk", "draining", "errors", "flakes",
98 "incidents", "lane", "machine", "memory", "needs", "ok", "optional", "queue", "rollout", "schedules", "stale",
98 "incidents", "lane", "machine", "memory", "needs", "ok", "optional", "queue", "release", "rollout", "schedules", "stale",
9999 "stuck",
100100 "todo", "version",
101101 ].sort(),
@@ -115,7 +115,7 @@ test("a site admin with a read-only token gets the shape; others get the short o
115115 expect(short["rollout"]).toBeDefined();
116116 // A stranger is told whether it is well, and no more (#2917).
117117 const stranger = (await (await health()).json()) as Record<string, unknown>;
118 expect(Object.keys(stranger).sort()).toEqual(["commit", "draining", "ok", "schedules", "version"]);
118 expect(Object.keys(stranger).sort()).toEqual(["commit", "draining", "ok", "release", "schedules", "version"]);
119119 expect((await fetch(servers.url + "/healthz")).status).toBe(200);
120120 });
121121

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs