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

src/kernel imports nothing outside src/kernel, held by a rule test with today's exceptions named #13650

Merged opened this

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

Merged

mason/forge:mason/13646-src-kernel-imports-nothing-outside-src-k → main 1 commit fork

  • Merged. mason/13646-src-kernel-imports-nothing-outside-src-k was merged into main as bf20962.

Review

Sign in to review this change.
1 file changed +145 −0
test/kernel-boundary.test.ts added +145
@@ -0,0 +1,145 @@
1 /**
2 * The kernel's boundary (#13646, step 7 of #13639): `src/kernel/` is the
3 * forge's first package, and it imports nothing outside itself but the
4 * runtime (`node:*`, `bun:*`). Each import that leaves it today is named in
5 * {@link CROSSINGS} with one line why; any other — a new kernel file, or a
6 * new line in an old one — is red here, and a crossing that is gone must
7 * leave the list, so the list only shrinks. Removing the rest is later work.
8 *
9 * Reads files; boots nothing.
10 *
11 * @tree-scan: lists src/kernel/ through a parameter's default.
12 */
13
14 import { describe, expect, test } from "bun:test";
15 import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
16 import { tmpdir } from "node:os";
17 import { dirname, join, relative, resolve, sep } from "node:path";
18 import { breaches } from "./helpers/rule.ts";
19
20 const KERNEL = resolve(import.meta.dir, "..", "src", "kernel");
21
22 /** Each import that leaves the kernel today, `file -> specifier`, and why it still does. */
23 const CROSSINGS: Readonly<Record<string, string>> = {
24 "full_disk.ts -> ../perf/jobs.ts": "names the job running when the disk filled",
25 "guard.ts -> ../http/health.ts": "the guard answers with the health verdict",
26 "outbound.ts -> ../apps/egress.ts": "the cell proxy and its refusal words live with the apps' egress",
27 "preflight.ts -> ../settings/signup.ts": "preflight checks the signup setting read from the env",
28 "worker_ask.ts -> ../perf/memory_watch.ts": "a worker's answer carries its memory reading",
29 "vitals.ts -> ../perf/memory_watch.ts": "the standing says when memory grew",
30 "vitals.ts -> ../spawn/disk_floor.ts": "the standing holds the disk to the spawn floor",
31 "vitals.ts -> ../core/runs.ts": "the standing counts the queue, leases and budget failures",
32 "vitals.ts -> ../runs/held.ts": "the standing names held runs",
33 "vitals.ts -> ../runs/lease.ts": "the standing uses the lease's stale age",
34 "vitals.ts -> ../system/db_size.ts": "the standing reports the database's size and growth",
35 "vitals.ts -> ../snapshot/bucket.ts": "the standing reports whether backups are watched",
36 "vitals.ts -> ../snapshot/drills.ts": "the standing reports the last restore drill",
37 "vitals.ts -> ../snapshot/mirror.ts": "the standing reports the last mirror",
38 "vitals.ts -> ../snapshot/outcome.ts": "the standing reports the last snapshot",
39 "vitals.ts -> ../snapshot/verdict.ts": "the standing reports the drill verdict",
40 "vitals.ts -> ../release/prove.ts": "the standing names leftover release probes",
41 "vitals.ts -> ../release/launch.ts": "the standing asks for a rollback when one is due",
42 "vitals.ts -> ../release/behind.ts": "the standing says when production is behind main",
43 "vitals.ts -> ../core/domain_drills.ts": "the standing reports the newest domain drills",
44 "vitals.ts -> ../core/capacity.ts": "the standing reads the machine's limits and use",
45 "vitals.ts -> ../system/memory_limit.ts": "the standing reads the memory limit",
46 "vitals.ts -> ../settings/limits.ts": "the standing reads the configured limits",
47 "vitals.ts -> ../http/access_log.ts": "the standing says when the access log went silent",
48 "vitals.ts -> ../checks/red_main.ts": "the standing says when main is red",
49 "vitals.ts -> ../checks/disk_red.ts": "the standing names checks red for lack of disk",
50 "vitals.ts -> ../checks/flake.ts": "the standing lists flaky tests",
51 "vitals.ts -> ../checks/shared_red.ts": "the standing names a cause shared by red checks",
52 };
53
54 /** A static import or re-export, type-only ones too, opening its line. */
55 const STATEMENT = /^(?:import|export)\b[^;'"`]*?\bfrom\s*["']([^"']+)["']|^import\s*["']([^"']+)["']/gm;
56
57 /** The runtime's own modules: not a crossing. */
58 const RUNTIME = /^(?:node|bun):/;
59
60 /** The specifiers `source` imports: static, type-only, re-exported and dynamic. */
61 export function specifiers(source: string): string[] {
62 const found = new Set<string>();
63 const text = source.replace(/^#!.*/, "");
64 for (const { path } of new Bun.Transpiler({ loader: "ts" }).scanImports(text)) found.add(path);
65 for (const m of text.matchAll(STATEMENT)) found.add(m[1] ?? m[2] ?? "");
66 found.delete("");
67 return [...found];
68 }
69
70 /** Every import in `dir`'s own `.ts` files that leaves `dir`, as `file -> specifier`. */
71 export function crossings(dir: string = KERNEL): string[] {
72 const out: string[] = [];
73 for (const name of readdirSync(dir).sort()) {
74 if (!name.endsWith(".ts") || name.endsWith(".d.ts")) continue;
75 const file = join(dir, name);
76 for (const path of specifiers(readFileSync(file, "utf8"))) {
77 if (RUNTIME.test(path)) continue;
78 const target = path.startsWith(".") ? resolve(dirname(file), path) : undefined;
79 if (target !== undefined && target.startsWith(dir + sep)) continue;
80 out.push(`${relative(dir, file)} -> ${path}`);
81 }
82 }
83 return out;
84 }
85
86 const found = crossings();
87
88 describe("src/kernel imports nothing outside src/kernel but what CROSSINGS names", () => {
89 breaches(
90 "clean",
91 found.filter((c) => !(c in CROSSINGS)).map((c) => `src/kernel/${c}: not in CROSSINGS`),
92 );
93 });
94
95 describe("every crossing CROSSINGS names is still made, so the list only shrinks", () => {
96 breaches(
97 "clean",
98 Object.keys(CROSSINGS)
99 .filter((c) => !found.includes(c))
100 .map((c) => `${c}: gone, take it out of CROSSINGS`),
101 );
102 });
103
104 test("each crossing says why in one line", () => {
105 for (const why of Object.values(CROSSINGS)) {
106 expect(why.trim().length).toBeGreaterThan(0);
107 expect(why).not.toContain("\n");
108 }
109 });
110
111 test("a new kernel file importing from outside the kernel is a crossing", () => {
112 const root = mkdtempSync(join(tmpdir(), "kernel-boundary-"));
113 const kernel = join(root, "kernel");
114 try {
115 mkdirSync(kernel);
116 writeFileSync(
117 join(kernel, "fresh.ts"),
118 [
119 'import { statSync } from "node:fs";',
120 'import type { Database } from "bun:sqlite";',
121 'import { ok } from "./result.ts";',
122 'import type { Run } from "../core/runs.ts";',
123 "import {",
124 " a,",
125 " type B,",
126 '} from "../http/health.ts";',
127 'export { c } from "../apps/egress.ts";',
128 'import "../web/side.ts";',
129 'const m = await import("../perf/jobs.ts");',
130 'import { z } from "zod";',
131 "/**",
132 ' * import { nope } from "../in/a/comment.ts";',
133 " */",
134 "console.log(statSync, ok, a, m, z);",
135 ].join("\n"),
136 );
137 writeFileSync(join(kernel, "result.ts"), "export const ok = 1;\n");
138 expect(crossings(kernel).map((c) => c.split(" -> ")[1]).sort()).toEqual(
139 ["../apps/egress.ts", "../core/runs.ts", "../http/health.ts", "../perf/jobs.ts", "../web/side.ts", "zod"].sort(),
140 );
141 expect(crossings(kernel).every((c) => c.startsWith("fresh.ts -> "))).toBe(true);
142 } finally {
143 rmSync(root, { recursive: true, force: true });
144 }
145 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs