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

A boot on a database the first paint cannot read says which health check fails, and why, in the app's log #213

Merged opened this

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

Merged

mason/deal-clock:mason/205-a-boot-on-a-database-the-first-paint-can → main 6 commits fork 4 threads · 4 unresolved

  • Merged. mason/205-a-boot-on-a-database-the-first-paint-can was merged into main as 7e02c5c.

Review

Sign in to review this change.
3 files changed +75 −7
src/health.test.ts +46 −2
@@ -1,7 +1,12 @@
1 import { expect, test } from "bun:test";
1 import { expect, spyOn, test } from "bun:test";
22 import { Database } from "bun:sqlite";
3 import { migrate, migrations } from "./db.ts";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { migrate, migrations, openDb } from "./db.ts";
7 import { serve } from "./server.ts";
48 import { routes } from "./routes.ts";
9 import { failedCheckDetail } from "./health.ts";
510
611 const handler = routes.find((r) => r.path === "/healthz")!.handle as (c: unknown) => Response;
712 const ask = (db: Database) => handler({ db });
@@ -49,3 +54,42 @@ test("a database missing a table the waiting count reads answers 503 naming wait
4954 expect(response.status).toBe(503);
5055 expect(((await response.json()) as { failed: string }).failed).toBe("waiting");
5156 });
57
58 test("the failed-check detail names the check and the database's own message; a fresh database has none", () => {
59 const fresh = new Database(":memory:");
60 migrate(fresh);
61 expect(failedCheckDetail(fresh)).toBeNull();
62 const db = new Database(":memory:");
63 migrate(db);
64 db.exec("ALTER TABLE deadline DROP COLUMN place");
65 const detail = failedCheckDetail(db);
66 expect(detail?.name).toBe("dates");
67 expect(detail?.message).toMatch(/no such column: place/);
68 });
69
70 // What the boot writes to stderr, from `serve` on a database in a fresh directory.
71 function bootLog(breakIt?: (db: Database) => void): string[] {
72 const dir = mkdtempSync(join(tmpdir(), "app-health-boot-"));
73 if (breakIt !== undefined) {
74 const db = openDb(dir);
75 breakIt(db);
76 db.close();
77 }
78 const errors = spyOn(console, "error").mockImplementation(() => {});
79 try {
80 serve({ port: 0, dataDir: dir, identityKey: "k" }).stop(true);
81 return errors.mock.calls.map((args) => args.join(" "));
82 } finally {
83 errors.mockRestore();
84 }
85 }
86
87 test("a boot on a database missing a column the first paint reads logs the check and the database's message", () => {
88 const lines = bootLog((db) => db.exec("ALTER TABLE deadline DROP COLUMN place"));
89 expect(lines).toHaveLength(1);
90 expect(lines[0]).toMatch(/health check "dates" fails at boot: .*no such column: place/);
91 });
92
93 test("a healthy boot writes nothing to stderr", () => {
94 expect(bootLog()).toEqual([]);
95 });
src/health.ts +27 −5
@@ -24,15 +24,37 @@ const CHECKS: readonly (readonly [name: string, sql: string])[] = [
2424 ],
2525 ];
2626
27 /** The name of the first check that throws, else null. Never the error: it can carry SQL. */
28 export function failedCheck(db: Database): string | null {
27 /**
28 * The first check that throws, with the database's own message, else null.
29 * For the log only: the message can carry SQL and must never reach an HTTP answer.
30 */
31 export function failedCheckDetail(db: Database): { name: string; message: string } | null {
2932 for (const [name, sql] of CHECKS) {
3033 try {
3134 db.query(sql).get();
32 } catch {
33 // Neither the error nor the SQL leaves: the answer names the check and nothing else.
34 return name;
35 } catch (error) {
36 return { name, message: error instanceof Error ? error.message : String(error) };
3537 }
3638 }
3739 return null;
3840 }
41
42 /** The name of the first check that throws, else null. Never the error: it can carry SQL. */
43 export function failedCheck(db: Database): string | null {
44 // Neither the error nor the SQL leaves: the answer names the check and nothing else.
45 return failedCheckDetail(db)?.name ?? null;
46 }
47
48 /**
49 * The same checks `/healthz` runs, once at boot, so the cause of a 503 is in
50 * the log: the failing check's name and the database's own message. Writes one
51 * line to `log` when a check fails and nothing when all pass. Reads only.
52 */
53 export function reportHealthAtBoot(
54 db: Database,
55 title: string,
56 log: (line: string) => void = console.error,
57 ): void {
58 const failed = failedCheckDetail(db);
59 if (failed !== null) log(`${title}: health check "${failed.name}" fails at boot: ${failed.message}`);
60 }
src/server.ts +2
@@ -9,6 +9,7 @@
99
1010 import { openDb } from "./db.ts";
1111 import { dataDir, identityKey, title, where } from "./env.ts";
12 import { reportHealthAtBoot } from "./health.ts";
1213 import { html, sourceBytes, text } from "./http.ts";
1314 import { follow } from "./live.ts";
1415 import { match, notFound } from "./routes.ts";
@@ -24,6 +25,7 @@ export interface ServeOptions {
2425
2526 export function serve(options: ServeOptions) {
2627 const db = openDb(options.dataDir);
28 reportHealthAtBoot(db, title);
2729 // The terminal writes from its own process: when the file changes under
2830 // us, every open page hears it, as if the change were made here.
2931 const unfollow = follow(

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs