Public: anyone can read this; the crew can change it.
Production's health counts the schedules its own forge.json declares, so the schedule line of the v1 proof can pass #15609
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15605-production-s-health-counts-the-schedules → main 0 commits fork
5 files
changed +235
−4
src/actions/health.ts +5 −1
| @@ -25,6 +25,7 @@ import { appsRuntime } from "../apps/runtime.ts"; | ||
| 25 | 25 | import { listApps } from "../core/apps.ts"; |
| 26 | 26 | import { ledgerNeed } from "../core/ledger.ts"; |
| 27 | 27 | import { overdueSchedules, type ScheduleCounts } from "../core/timers.ts"; |
| 28 | import { addCounts, ownScheduleCounts, ownSchedules, readOwnRuns } from "../core/own_schedules.ts"; | |
| 28 | 29 | import type { User } from "../core/users.ts"; |
| 29 | 30 | import { forgeHealth, rolloutLine, type ForgeHealth } from "../kernel/guard.ts"; |
| 30 | 31 | import { |
| @@ -149,7 +150,10 @@ export function healthAnswer( | ||
| 149 | 150 | probe = false, |
| 150 | 151 | now: number = Date.now(), |
| 151 | 152 | ): ReturnType<typeof readHealth> & ReleaseHealth & ScheduleHealth { |
| 152 | const schedules = overdueSchedules(app.db, now); | |
| 153 | // The hosted apps' schedules, and this forge's own that its host fires (#15605). | |
| 154 | const own = ownSchedules(); | |
| 155 | const hosted = overdueSchedules(app.db, now); | |
| 156 | const schedules = own.length === 0 ? hosted : addCounts(hosted, ownScheduleCounts(own, readOwnRuns(app.config.dataDir), now)); | |
| 153 | 157 | return { ...readHealth(app, actor, probe), release: releaseOf(), schedules }; |
| 154 | 158 | } |
| 155 | 159 |
src/core/own_schedules.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * The forge's own schedules (#15605): the ones this repository's `forge.json` declares, armed and | |
| 3 | * fired by the host forge that runs this one as an app. Their timer rows live in the host's | |
| 4 | * database, never in this forge's, so `overdueSchedules` (which reads this forge's `timer` table, | |
| 5 | * the schedules of the apps it hosts) cannot see them. This module counts them from what this | |
| 6 | * forge can see: the declaration, and the signed calls the host made to it. | |
| 7 | * | |
| 8 | * Counted only when a host runs this forge (`FORGE_APP_IDENTITY_KEY` set, the key it signs with): | |
| 9 | * a forge nobody hosts has nobody to fire its own schedules. Only those of the environment it runs | |
| 10 | * as (`FORGE_APP_ENV`, production by default) count, as the host arms only those. | |
| 11 | * | |
| 12 | * A run is a signed call the forge answered 2xx, written to `own-schedules.json` under the data | |
| 13 | * directory as `{ path: lastMs }`. Counts out, never a name or path. | |
| 14 | */ | |
| 15 | ||
| 16 | import { readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 17 | import { join } from "node:path"; | |
| 18 | import { nextRun, parseCron } from "../apps/cron.ts"; | |
| 19 | import { parseSchedules, type ScheduleSpec } from "../apps/schedule_spec.ts"; | |
| 20 | import { OVERDUE_AFTER_MS, type ScheduleCounts } from "./timers.ts"; | |
| 21 | ||
| 22 | type Env = Record<string, string | undefined>; | |
| 23 | export type OwnRuns = Readonly<Record<string, number>>; | |
| 24 | ||
| 25 | const RUNS_FILE = "own-schedules.json"; | |
| 26 | ||
| 27 | /** | |
| 28 | * The schedules a `forge.json` text declares for `env`; none when it declares none or is not valid. | |
| 29 | */ | |
| 30 | export function declaredSchedules(forgeJson: string, env: "production" | "preview"): readonly ScheduleSpec[] { | |
| 31 | let parsed: unknown; | |
| 32 | try { | |
| 33 | parsed = JSON.parse(forgeJson); | |
| 34 | } catch { | |
| 35 | return []; | |
| 36 | } | |
| 37 | const raw = typeof parsed === "object" && parsed !== null ? (parsed as Record<string, unknown>)["schedules"] : undefined; | |
| 38 | if (raw === undefined) return []; | |
| 39 | const specs = parseSchedules(raw); | |
| 40 | return specs.ok ? specs.value.filter((s) => s.env === env) : []; | |
| 41 | } | |
| 42 | ||
| 43 | let cached: readonly ScheduleSpec[] | undefined; | |
| 44 | ||
| 45 | /** | |
| 46 | * This repository's declared schedules for the environment it runs as, when a host runs it; read | |
| 47 | * once. | |
| 48 | */ | |
| 49 | export function ownSchedules(env: Env = process.env): readonly ScheduleSpec[] { | |
| 50 | if ((env.FORGE_APP_IDENTITY_KEY ?? "").trim() === "") return []; | |
| 51 | if (cached !== undefined) return cached; | |
| 52 | const as = (env.FORGE_APP_ENV ?? "").trim().toLowerCase() === "preview" ? "preview" : "production"; | |
| 53 | let text = ""; | |
| 54 | try { | |
| 55 | text = readFileSync(join(import.meta.dir, "..", "..", "forge.json"), "utf8"); | |
| 56 | } catch { | |
| 57 | text = ""; | |
| 58 | } | |
| 59 | cached = declaredSchedules(text, as); | |
| 60 | return cached; | |
| 61 | } | |
| 62 | ||
| 63 | /** The recorded runs under `dataDir`; none when the file is missing or not ours. */ | |
| 64 | export function readOwnRuns(dataDir: string): OwnRuns { | |
| 65 | try { | |
| 66 | const v = JSON.parse(readFileSync(join(dataDir, RUNS_FILE), "utf8")) as unknown; | |
| 67 | if (typeof v !== "object" || v === null || Array.isArray(v)) return {}; | |
| 68 | const out: Record<string, number> = {}; | |
| 69 | for (const [k, n] of Object.entries(v)) if (typeof n === "number" && Number.isFinite(n)) out[k] = n; | |
| 70 | return out; | |
| 71 | } catch { | |
| 72 | return {}; | |
| 73 | } | |
| 74 | } | |
| 75 | ||
| 76 | /** Note that the host's call to `path` was answered 2xx at `now`; a declared path only. */ | |
| 77 | export function recordOwnRun(dataDir: string, specs: readonly ScheduleSpec[], path: string, now: number): void { | |
| 78 | if (!specs.some((s) => s.path === path)) return; | |
| 79 | const runs = { ...readOwnRuns(dataDir), [path]: now }; | |
| 80 | const file = join(dataDir, RUNS_FILE); | |
| 81 | writeFileSync(`${file}.tmp`, JSON.stringify(runs), { mode: 0o600 }); | |
| 82 | renameSync(`${file}.tmp`, file); | |
| 83 | } | |
| 84 | ||
| 85 | /** | |
| 86 | * Counts for `specs` given their runs: each is one of `total`; one with a run is `ran`; one whose | |
| 87 | * next occurrence after its last run is more than `OVERDUE_AFTER_MS` gone is overdue. One that | |
| 88 | * never ran is not judged overdue here: when the host armed it is the host's to know. | |
| 89 | */ | |
| 90 | export function ownScheduleCounts(specs: readonly ScheduleSpec[], runs: OwnRuns, now: number): ScheduleCounts { | |
| 91 | let ran = 0; | |
| 92 | let overdue = 0; | |
| 93 | let oldest: number | undefined; | |
| 94 | for (const s of specs) { | |
| 95 | const last = runs[s.path]; | |
| 96 | if (last === undefined) continue; | |
| 97 | ran++; | |
| 98 | const cron = parseCron(s.cron); | |
| 99 | const due = cron.ok ? nextRun(cron.value, s.timezone, last) : undefined; | |
| 100 | if (due !== undefined && due < now - OVERDUE_AFTER_MS) { | |
| 101 | overdue++; | |
| 102 | oldest = oldest === undefined ? due : Math.min(oldest, due); | |
| 103 | } | |
| 104 | } | |
| 105 | return { overdue, oldestSeconds: oldest === undefined ? 0 : Math.floor((now - oldest) / 1000), total: specs.length, ran }; | |
| 106 | } | |
| 107 | ||
| 108 | /** Two sets of counts as one: the hosted apps' and the forge's own. */ | |
| 109 | export function addCounts(a: ScheduleCounts, b: ScheduleCounts): ScheduleCounts { | |
| 110 | return { overdue: a.overdue + b.overdue, oldestSeconds: Math.max(a.oldestSeconds, b.oldestSeconds), total: a.total + b.total, ran: a.ran + b.ran }; | |
| 111 | } |
src/http/heartbeat.ts +2 −1
| @@ -4,7 +4,8 @@ | ||
| 4 | 4 | * the production forge, so that one declared schedule is the production forge's proof that its |
| 5 | 5 | * clock fires with no person involved (`/api/v1/health` `schedules.total` and `.ran`). |
| 6 | 6 | * |
| 7 | * It does nothing but answer: no state written, no model called, no money spent. It answers 200 | |
| 7 | * It does nothing but answer: no model called, no money spent; the server notes a 2xx as the | |
| 8 | * forge's own schedule having run (`core/own_schedules.ts`, #15605). It answers 200 | |
| 8 | 9 | * only to a call the host forge signed (`timer_fire.ts` `callHeaders`: `x-forge-identity` is |
| 9 | 10 | * `forge-timer|<idempotency key>|timer|<expiry ms>`, `x-forge-signature` its HMAC-SHA256 in |
| 10 | 11 | * base64url under `FORGE_APP_IDENTITY_KEY`), unexpired; anything else is a 401 that says why. |
src/http/server.ts +13 −2
| @@ -113,6 +113,7 @@ import { shieldState } from "../actions/shield.ts"; | ||
| 113 | 113 | import { crawlRefused, familyOf, finishedStrangerDeep, isCrawler, isDeepPath, isShieldedPath, noteCrawler, noteDeepStranger, noteShielded, shieldRefused, takeCrawl, wasCrawler, wasDeepStranger, wasShielded } from "./crawl.ts"; |
| 114 | 114 | import { liveResponse, readyResponse } from "./health.ts"; |
| 115 | 115 | import { HEARTBEAT_PATH, heartbeatAnswer, heartbeatKey } from "./heartbeat.ts"; |
| 116 | import { ownSchedules, recordOwnRun } from "../core/own_schedules.ts"; | |
| 116 | 117 | import { isRead, readOnlyRefusal } from "./read_only.ts"; |
| 117 | 118 | import { fullRefusal, isFullError, noteFull } from "../kernel/full_disk.ts"; |
| 118 | 119 | import { running } from "../kernel/version.ts"; |
| @@ -3420,10 +3421,20 @@ async function answer( | ||
| 3420 | 3421 | noteUsage(request, { pattern: "/readyz", role: "anon" }); |
| 3421 | 3422 | return readyResponse(); |
| 3422 | 3423 | } |
| 3423 | // The host forge's daily heartbeat schedule (#15499): signed, server to server, writes nothing. | |
| 3424 | // The host forge's daily heartbeat schedule (#15499): signed, server to server; a 2xx is | |
| 3425 | // noted as the forge's own schedule having run, for health's counts (#15605). | |
| 3424 | 3426 | if (url.pathname === HEARTBEAT_PATH) { |
| 3425 | 3427 | noteUsage(request, { pattern: HEARTBEAT_PATH, role: "anon" }); |
| 3426 | return heartbeatAnswer(request, heartbeatKey()); | |
| 3428 | const now = Date.now(); | |
| 3429 | const answer = heartbeatAnswer(request, heartbeatKey(), now); | |
| 3430 | if (answer.status === 200) { | |
| 3431 | try { | |
| 3432 | recordOwnRun(app.config.dataDir, ownSchedules(), HEARTBEAT_PATH, now); | |
| 3433 | } catch (e) { | |
| 3434 | console.error(`heartbeat: the run could not be noted: ${e instanceof Error ? e.message : String(e)}`); | |
| 3435 | } | |
| 3436 | } | |
| 3437 | return answer; | |
| 3427 | 3438 | } |
| 3428 | 3439 | const routeMethod = request.method === "HEAD" ? "GET" : request.method; |
| 3429 | 3440 | // The one place a path decides its own shape of miss: anything under |
test/own-schedules.test.ts added +104
| @@ -0,0 +1,104 @@ | ||
| 1 | /** | |
| 2 | * The forge's own schedules on its health answer (#15605): production is this forge run as an | |
| 3 | * app of another, so its heartbeat's timer row lives in the host's database and the local count | |
| 4 | * read 0. Health now adds the schedules this repository's forge.json declares, when a host runs | |
| 5 | * it, and counts the host's signed calls as their runs. Counts only, never a name or path. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { readFileSync } from "node:fs"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { callHeaders } from "../src/apps/timer_fire.ts"; | |
| 14 | import { addCounts, declaredSchedules, ownScheduleCounts, ownSchedules, readOwnRuns, recordOwnRun } from "../src/core/own_schedules.ts"; | |
| 15 | import { OVERDUE_AFTER_MS } from "../src/core/timers.ts"; | |
| 16 | import { HEARTBEAT_PATH } from "../src/http/heartbeat.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | ||
| 19 | const KEY = "k".repeat(43); | |
| 20 | const ONE = JSON.stringify({ schedules: [{ name: "beat", cron: "5 7 * * *", timezone: "UTC", path: "/jobs/beat" }] }); | |
| 21 | const NOW = Date.UTC(2026, 10, 22, 12, 0); | |
| 22 | ||
| 23 | let dataDir: string; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | const saved = { key: process.env.FORGE_APP_IDENTITY_KEY, env: process.env.FORGE_APP_ENV }; | |
| 27 | ||
| 28 | beforeAll(async () => { | |
| 29 | process.env.FORGE_APP_IDENTITY_KEY = KEY; | |
| 30 | delete process.env.FORGE_APP_ENV; | |
| 31 | dataDir = await mkdtemp(join(tmpdir(), "forge-own-schedules-")); | |
| 32 | app = createApp({ dataDir, port: 0, disk: () => ({ freeBytes: 95, totalBytes: 100 }) }); | |
| 33 | servers = await serve(app); | |
| 34 | }); | |
| 35 | afterAll(async () => { | |
| 36 | servers.stop(); | |
| 37 | app.close(); | |
| 38 | await rm(dataDir, { recursive: true, force: true }); | |
| 39 | if (saved.key === undefined) delete process.env.FORGE_APP_IDENTITY_KEY; | |
| 40 | else process.env.FORGE_APP_IDENTITY_KEY = saved.key; | |
| 41 | if (saved.env !== undefined) process.env.FORGE_APP_ENV = saved.env; | |
| 42 | }); | |
| 43 | ||
| 44 | test("one declared schedule: total is 1, not 0, and ran 0 until it runs", () => { | |
| 45 | const specs = declaredSchedules(ONE, "production"); | |
| 46 | expect(specs.length).toBe(1); | |
| 47 | expect(ownScheduleCounts(specs, {}, NOW)).toEqual({ overdue: 0, oldestSeconds: 0, total: 1, ran: 0 }); | |
| 48 | expect(ownScheduleCounts(specs, { "/jobs/beat": Date.UTC(2026, 10, 22, 7, 5) }, NOW)).toEqual({ overdue: 0, oldestSeconds: 0, total: 1, ran: 1 }); | |
| 49 | }); | |
| 50 | ||
| 51 | test("a schedule whose last run is past its period is overdue 1, with its age", () => { | |
| 52 | const specs = declaredSchedules(ONE, "production"); | |
| 53 | const last = Date.UTC(2026, 10, 20, 7, 5); | |
| 54 | const due = Date.UTC(2026, 10, 21, 7, 5); | |
| 55 | const got = ownScheduleCounts(specs, { "/jobs/beat": last }, NOW); | |
| 56 | expect(got).toEqual({ overdue: 1, oldestSeconds: Math.floor((NOW - due) / 1000), total: 1, ran: 1 }); | |
| 57 | expect(ownScheduleCounts(specs, { "/jobs/beat": last }, due + OVERDUE_AFTER_MS - 1).overdue).toBe(0); | |
| 58 | }); | |
| 59 | ||
| 60 | test("only the environment's schedules count, and a bad forge.json declares none", () => { | |
| 61 | const both = JSON.stringify({ schedules: [{ name: "a", cron: "* * * * *", path: "/a" }, { name: "b", cron: "* * * * *", path: "/b", env: "preview" }] }); | |
| 62 | expect(declaredSchedules(both, "production").map((s) => s.name)).toEqual(["a"]); | |
| 63 | expect(declaredSchedules(both, "preview").map((s) => s.name)).toEqual(["b"]); | |
| 64 | expect(declaredSchedules("{nope", "production")).toEqual([]); | |
| 65 | expect(declaredSchedules("{}", "production")).toEqual([]); | |
| 66 | }); | |
| 67 | ||
| 68 | test("no host, no own schedules: nobody fires them", () => { | |
| 69 | expect(ownSchedules({})).toEqual([]); | |
| 70 | }); | |
| 71 | ||
| 72 | test("a run is noted only for a declared path", () => { | |
| 73 | const specs = declaredSchedules(ONE, "production"); | |
| 74 | recordOwnRun(dataDir, specs, "/elsewhere", NOW); | |
| 75 | expect(readOwnRuns(dataDir)).toEqual({}); | |
| 76 | recordOwnRun(dataDir, specs, "/jobs/beat", NOW); | |
| 77 | expect(readOwnRuns(dataDir)).toEqual({ "/jobs/beat": NOW }); | |
| 78 | }); | |
| 79 | ||
| 80 | test("counts add, the oldest is the worse of the two", () => { | |
| 81 | expect(addCounts({ overdue: 1, oldestSeconds: 9, total: 2, ran: 1 }, { overdue: 0, oldestSeconds: 0, total: 1, ran: 1 })).toEqual({ overdue: 1, oldestSeconds: 9, total: 3, ran: 2 }); | |
| 82 | }); | |
| 83 | ||
| 84 | test("hosted, the health answer counts this repository's forge.json schedules, and the host's signed heartbeat as their run", async () => { | |
| 85 | const declared = declaredSchedules(readFileSync(join(import.meta.dir, "..", "forge.json"), "utf8"), "production"); | |
| 86 | expect(declared.length).toBeGreaterThan(0); | |
| 87 | const read = async () => { | |
| 88 | const res = await fetch(servers.url + "/api/v1/health"); | |
| 89 | const text = await res.text(); | |
| 90 | for (const s of declared) { | |
| 91 | expect(text).not.toContain(s.name); | |
| 92 | expect(text).not.toContain(s.path); | |
| 93 | } | |
| 94 | return (JSON.parse(text) as { schedules: { total: number; ran: number; overdue: number } }).schedules; | |
| 95 | }; | |
| 96 | const before = await read(); | |
| 97 | expect(before.total).toBe(declared.length); | |
| 98 | expect(before.ran).toBe(0); | |
| 99 | const now = Date.now(); | |
| 100 | const beat = await fetch(servers.url + HEARTBEAT_PATH, { method: "POST", headers: callHeaders(KEY, "heartbeat", now, 1, now + 60_000, `app:heartbeat:${now}`) }); | |
| 101 | expect(beat.status).toBe(200); | |
| 102 | const after = await read(); | |
| 103 | expect(after).toMatchObject({ total: declared.length, ran: 1, overdue: 0 }); | |
| 104 | }); |
new above
offline