Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

recovery-probe.ts

111 lines3.6 KB

1import { migrate } from "../ingest/migrate";
2import { spawn, type ChildProcess } from "node:child_process";
3import { writeFile } from "node:fs/promises";
4import { setTimeout as delay } from "node:timers/promises";
5import { Pool } from "pg";
6const schema = `hn_recovery_${Date.now()}`;
7const admin = new Pool({ connectionString: process.env.DATABASE_URL_UNPOOLED });
8const url = new URL(process.env.DATABASE_URL_UNPOOLED!);
9url.searchParams.set("options", `-c search_path=${schema}`);
10const pool = new Pool({ connectionString: url.href });
11const children: ChildProcess[] = [];
12const results: Record<string, number> = {};
13const launch = () => {
14 const child = spawn(
15 process.execPath,
16 ["--import", "tsx", "scripts/ingest.ts"],
17 {
18 env: {
19 ...process.env,
20 DATABASE_URL: url.href,
21 INGEST_REQUEST_BUDGET_MS: "180000",
22 INGEST_TENURE_MS: "90000",
23 INGEST_OVERLAP_MS: "60000",
24 },
25 stdio: "ignore",
26 },
27 );
28 children.push(child);
29 return child;
30};
31async function waitFor(check: () => Promise<boolean>, limit = 120000) {
32 const until = Date.now() + limit;
33 while (Date.now() < until) {
34 if (await check()) return;
35 await delay(500);
36 }
37 throw new Error("Recovery probe timed out");
39const lease = async () =>
40 (await pool.query("SELECT * FROM ingest_leases WHERE id=1")).rows[0];
41try {
42 await admin.query(`CREATE SCHEMA ${schema}`);
43 await migrate(pool);
44 const first = launch();
45 await waitFor(
46 async () =>
47 (await pool.query("SELECT state FROM ingest_status WHERE id=1")).rows[0]
48 .state === "healthy",
49 );
50 const firstOwner = (await lease()).active_owner;
51 await delay(31000);
52 const standby = launch();
53 await waitFor(async () => (await lease()).standby_ready);
54 const warmStart = Date.now();
55 first.kill("SIGKILL");
56 await waitFor(async () => {
57 const state = await lease();
58 return (
59 state.active_owner !== firstOwner &&
60 (await pool.query("SELECT owner,state FROM ingest_status WHERE id=1"))
61 .rows[0].state === "healthy"
62 );
63 });
64 results.warmRecoveryMs = Date.now() - warmStart;
65 console.log("Warm recovery:", results.warmRecoveryMs, "ms");
66 const secondOwner = (await lease()).active_owner;
67 const coldStart = Date.now();
68 standby.kill("SIGKILL");
69 // Model the worst phase of the one-minute scheduler, with no prepared standby.
70 await delay(60000);
71 launch();
72 await waitFor(async () => {
73 const state = await lease();
74 const health = (
75 await pool.query("SELECT owner,state FROM ingest_status WHERE id=1")
76 ).rows[0];
77 return (
78 state.active_owner !== secondOwner &&
79 health.owner === state.active_owner &&
80 health.state === "healthy"
81 );
82 }, 60000);
83 results.coldRecoveryMs = Date.now() - coldStart;
84 console.log("Cold recovery:", results.coldRecoveryMs, "ms");
85 if (results.warmRecoveryMs > 120000 || results.coldRecoveryMs > 120000)
86 throw new Error("Recovery budget exceeded");
87 await writeFile(
88 new URL("../.local/recovery-results.json", import.meta.url),
89 JSON.stringify(
90 {
91 measuredAt: new Date().toISOString(),
92 environment:
93 "isolated staging schema, real HN source, local Node process killed with SIGKILL",
94 ...results,
95 },
96 null,
97 2,
98 ),
99 );
100} finally {
101 children.forEach((child) => {
102 if (child.exitCode === null) child.kill("SIGTERM");
103 });
104 await delay(2000);
105 children.forEach((child) => {
106 if (child.exitCode === null) child.kill("SIGKILL");
107 });
108 await pool.end();
109 await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
110 await admin.end();