Skip to content
704 linesCodeBlameRaw
1// node --test "scripts/deploy/*.test.mjs" (npm run test:deploy)
2import assert from "node:assert/strict";
3import { execFileSync } from "node:child_process";
4import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5import { tmpdir } from "node:os";
6import { join } from "node:path";
7import { test } from "node:test";
8
9import { isStaticElf } from "../build-runner.mjs";
10import {
11 DEPLOY_CONFIG,
12 baseInputs,
13 baseState,
14 baseTag,
15 contentHash,
16 lockFor,
17 pushImage,
18 pushedDigest,
19 readBaseLock,
20 registryHas,
21 removeDeployConfig,
22 runnerRef,
23 runnerTag,
24 writeDeployConfig,
25} from "./image.mjs";
26
27import {
28 annotation,
29 apiAuth,
30 commitFrom,
31 databaseOf,
32 liveCommit,
33 liveFromApi,
34 migrationFiles,
35 pendingAgainst,
36 pendingFrom,
37 pendingMigrations,
38 readLive,
39 versionFrom,
40} from "./cloudflare.mjs";
41import { changedNames, parseCargoLock, parseNpmLock, reaches } from "./lockfiles.mjs";
42import { decide, planJson, pool } from "./plan.mjs";
43import {
44 ROOT,
45 buildGroups,
46 cargoWorkspace,
47 findWranglerConfigs,
48 loadStack,
49 npmCiArgs,
50 npmWorkspace,
51 outsideImports,
52 pick,
53 problems,
54 resolveStack,
55 resolvedStack,
56 touches,
57 touchesBase,
58 touchesImage,
59} from "./stack.mjs";
60
61const stack = resolvedStack();
62const unit = (id) => stack.units.find((u) => u.id === id);
63
64// ── The manifest ──────────────────────────────────────────────────────────
65
66test("the manifest matches every wrangler config in the repository", () => {
67 assert.deepEqual(problems(stack, findWranglerConfigs()), []);
68});
69
70test("every wrangler.jsonc is found, and only checked-in ones", () => {
71 const configs = findWranglerConfigs();
72 assert.ok(configs.includes("services/events/wrangler.jsonc"));
73 assert.ok(configs.includes("apps/web/wrangler.jsonc"));
74 assert.ok(!configs.some((c) => c.includes("/build/")), "build output is not a unit");
75 assert.equal(configs.length, stack.units.length);
76});
77
78test("problems are found: an unlisted config, a later-stage binding, a wrong database, an unnamed KV", () => {
79 const broken = loadStack();
80 const events = broken.units.find((u) => u.id === "events");
81 events.stage = "front";
82 const identity = broken.units.find((u) => u.id === "identity");
83 identity.d1 = { database: "g1t-identity", migrations: "migrations" };
84 broken.resources = { kv: {} };
85 const found = problems(broken, [...findWranglerConfigs(), "services/new/wrangler.jsonc"]);
86 assert.ok(found.some((p) => p.includes("services/new/wrangler.jsonc is not in")));
87 assert.ok(found.some((p) => p.includes("binds to events (front), which ships after it")));
88 assert.ok(found.some((p) => p.startsWith("Unit identity: d1 is")));
89 assert.ok(found.some((p) => p.includes("has no name under resources.kv")));
90});
91
92test("stages follow bindings: nothing binds to a unit that ships after it", () => {
93 const order = stack.stages;
94 for (const u of stack.units) {
95 for (const target of u.bindsTo) {
96 const other = stack.units.find((o) => o.worker === target);
97 assert.ok(order.indexOf(other.stage) <= order.indexOf(u.stage), `${u.id} -> ${other.id}`);
98 }
99 }
100});
101
102test("Rust workers build with the shared script and the same wasm-opt level", () => {
103 for (const u of stack.units.filter((u) => u.kind === "rust-worker")) {
104 assert.equal(u.config.build.command, "node ../../scripts/build-rust-worker.mjs", u.id);
105 const toml = readFileSync(join(ROOT, u.path, "Cargo.toml"), "utf8");
106 assert.match(toml, /\[package\.metadata\.wasm-pack\.profile\.release\]\s*\nwasm-opt = \["-O1"\]/, u.id);
107 }
108});
109
110// ── What each unit is built from ──────────────────────────────────────────
111
112test("shared crates and packages are read from workspace metadata", () => {
113 assert.deepEqual(unit("events").dependsOn, ["crates/contracts", "crates/kit"]);
114 assert.deepEqual(unit("repos").dependsOn, ["crates/blobstore", "crates/contracts", "crates/kit", "crates/rules", "crates/scan", "crates/secrets"]);
115 assert.ok(unit("work").dependsOn.includes("crates/rules"));
116 assert.ok(unit("actions").dependsOn.includes("crates/actions"));
117 assert.ok(!unit("events").dependsOn.includes("crates/scan"));
118 assert.deepEqual(unit("web").dependsOn, ["packages/contracts", "packages/theme"]);
119 assert.deepEqual(unit("projects").dependsOn, ["packages/contracts"]);
120 assert.deepEqual(unit("pages").dependsOn, []);
121 assert.equal(unit("events").crate, "g1t-events");
122 assert.equal(unit("web").pkg, "@g1t/web");
123});
124
125test("the runner's image is built from the runner crate and what it uses, on the base its lock names", () => {
126 const runner = unit("runner");
127 // The runner bumps lockfiles with the scanner's lockfile parser (security updates).
128 assert.deepEqual(runner.image.dirs, ["crates/actions", "crates/runner", "crates/scan"]);
129 assert.deepEqual(runner.image.baseDirs, ["services/runner/base"]);
130 assert.ok(runner.dependsOn.includes("crates/runner"));
131 assert.ok(touchesImage(runner, ["crates/actions/src/expr.rs"]));
132 assert.ok(touchesImage(runner, ["services/runner/Dockerfile"]));
133 assert.ok(touchesImage(runner, ["services/runner/base.json"]));
134 assert.ok(touchesImage(runner, ["scripts/build-runner.mjs"]));
135 assert.ok(!touchesImage(runner, ["services/runner/src/index.ts"]));
136 // The base's Dockerfile reaches the image only through a new lock.
137 assert.ok(!touchesImage(runner, ["services/runner/base/Dockerfile"]));
138 assert.ok(touchesBase(runner, ["services/runner/base/Dockerfile"]));
139 assert.ok(!touchesBase(unit("events"), ["services/runner/base/Dockerfile"]));
140});
141
142// ── The runner's images ───────────────────────────────────────────────────
143
144test("services/runner/base.json records the base its folder builds", () => {
145 const runner = unit("runner");
146 const lock = readBaseLock(runner);
147 assert.ok(lock, "services/runner/base.json is missing: node scripts/deploy.mjs build-base");
148 assert.equal(
149 lock.inputs,
150 baseInputs(runner),
151 "services/runner/base changed since base.json was written: node scripts/deploy.mjs build-base, and commit base.json",
152 );
153 assert.match(lock.image, /^registry\.cloudflare\.com\/[0-9a-f]{32}\/g1t-runner:base-\d{8}-[0-9a-f]{12}$/);
154 assert.ok(lock.image.endsWith(lock.inputs.slice(0, 12)));
155 assert.equal(baseState(runner).current, true);
156});
157
158test("an image's hash ignores line endings, and its tags say what they are", () => {
159 const files = { "a.txt": "one\r\ntwo\r\n", "b.txt": "x" };
160 const lf = { "a.txt": "one\ntwo\n", "b.txt": "x" };
161 const hash = (set) => contentHash(Object.keys(set), "/", (file) => Buffer.from(set[file]));
162 assert.equal(hash(files), hash(lf));
163 assert.notEqual(hash(lf), hash({ ...lf, "b.txt": "y" }));
164 assert.equal(baseTag("0123456789abcdef".repeat(4), new Date("2026-10-06T12:00:00Z")), "base-20261006-0123456789ab");
165 const runner = unit("runner");
166 assert.match(runnerTag(runner), /^[0-9a-f]{16}$/);
167 assert.equal(runnerTag(runner), runnerTag(runner));
168 assert.equal(runnerRef(runner, ROOT, "a".repeat(32)), `registry.cloudflare.com/${"a".repeat(32)}/g1t-runner:${runnerTag(runner)}`);
169});
170
171test("only the lockfile entries the runner is built from name its image", () => {
172 const lock = (wasm) => `[[package]]
173name = "g1t-runner"
174version = "0.1.0"
175dependencies = [
176 "ureq",
177]
178
179[[package]]
180name = "ureq"
181version = "2.12.1"
182
183[[package]]
184name = "wasm-bindgen"
185version = "${wasm}"
186`;
187 assert.equal(lockFor(lock("0.2.100"), "g1t-runner"), lockFor(lock("0.2.101"), "g1t-runner"));
188 assert.ok(lockFor(lock("0.2.100"), "g1t-runner").includes("ureq"));
189 assert.notEqual(lockFor(lock("0.2.100"), "g1t-runner"), lockFor(lock("0.2.100").replace("2.12.1", "2.12.2"), "g1t-runner"));
190});
191
192test("the runner's deploy config names its image by reference, beside its wrangler.jsonc", () => {
193 const runner = unit("runner");
194 const ref = "registry.cloudflare.com/acct/g1t-runner:0123456789abcdef";
195 const name = writeDeployConfig(runner, ref);
196 try {
197 assert.equal(name, DEPLOY_CONFIG);
198 const config = JSON.parse(readFileSync(join(ROOT, runner.path, DEPLOY_CONFIG), "utf8"));
199 assert.equal(config.name, "g1t-runner");
200 assert.equal(config.main, "./src/index.ts");
201 assert.ok(config.containers.length >= 1);
202 for (const container of config.containers) {
203 assert.equal(container.image, ref);
204 assert.equal(container.image_build_context, undefined);
205 }
206 // Every sandbox class shares the image; each has a Durable Object binding.
207 const classes = config.containers.map((c) => c.class_name).sort();
208 assert.deepEqual(classes, config.durable_objects.bindings.map((b) => b.class_name).sort());
209 // Generated, never committed, and not taken for a unit of its own.
210 assert.ok(readFileSync(join(ROOT, ".gitignore"), "utf8").includes("wrangler.deploy.json"));
211 assert.ok(!findWranglerConfigs().some((c) => c.endsWith(DEPLOY_CONFIG)));
212 } finally {
213 removeDeployConfig(runner);
214 }
215 assert.ok(!existsSync(join(ROOT, runner.path, DEPLOY_CONFIG)));
216});
217
218test("the registry is asked for an image's manifest, without Docker", async () => {
219 const asked = [];
220 const fetchImpl = async (url, init) => {
221 asked.push([url, init.method, init.headers.authorization]);
222 return { status: url.endsWith(":nope") || url.endsWith("/nope") ? 404 : 200, ok: !url.endsWith("/nope") };
223 };
224 const credentials = async () => ({ username: "v1", password: "secret" });
225 assert.equal(await registryHas("registry.cloudflare.com/acct/g1t-runner:abc", { fetchImpl, credentials }), true);
226 assert.equal(await registryHas("registry.cloudflare.com/acct/g1t-runner:nope", { fetchImpl, credentials }), false);
227 assert.deepEqual(asked[0], [
228 "https://registry.cloudflare.com/v2/acct/g1t-runner/manifests/abc",
229 "HEAD",
230 `Basic ${Buffer.from("v1:secret").toString("base64")}`,
231 ]);
232 await assert.rejects(registryHas("not-a-reference", { fetchImpl, credentials }));
233});
234
235test("a push counts only when it ends with a digest, and is tried again", async () => {
236 const digest = "sha256:" + "a".repeat(64);
237 assert.equal(pushedDigest({ code: 0, out: `base: digest: ${digest} size: 856` }), digest);
238 assert.equal(pushedDigest({ code: 0, out: "error from registry: blob unknown to registry" }), null);
239 assert.equal(pushedDigest({ code: 1, out: `digest: ${digest}` }), null);
240 assert.equal(pushedDigest({ code: 0, out: "Pushed" }), null);
241 const answers = [{ code: 1, out: "error from registry: blob unknown to registry" }, { code: 0, out: `x: digest: ${digest} size: 1` }];
242 assert.equal(await pushImage("r/x:y", { run: async () => answers.shift() }), digest);
243 await assert.rejects(pushImage("r/x:y", { attempts: 2, run: async () => ({ code: 0, out: "blob unknown" }) }), /docker push r\/x:y failed/);
244});
245
246test("a static Linux binary is told from a dynamic one", () => {
247 const dir = mkdtempSync(join(tmpdir(), "g1t-elf-"));
248 try {
249 const elf = (interp) => {
250 // 64-bit little-endian x86-64 ELF with one program header.
251 const bytes = Buffer.alloc(64 + 56);
252 bytes.writeUInt32BE(0x7f454c46, 0);
253 bytes[4] = 2;
254 bytes[5] = 1;
255 bytes.writeUInt16LE(0x3e, 18);
256 bytes.writeBigUInt64LE(64n, 32);
257 bytes.writeUInt16LE(56, 54);
258 bytes.writeUInt16LE(1, 56);
259 bytes.writeUInt32LE(interp ? 3 : 1, 64);
260 return bytes;
261 };
262 writeFileSync(join(dir, "static"), elf(false));
263 writeFileSync(join(dir, "dynamic"), elf(true));
264 writeFileSync(join(dir, "text"), "#!/bin/sh\n");
265 assert.equal(isStaticElf(join(dir, "static")), true);
266 assert.equal(isStaticElf(join(dir, "dynamic")), false);
267 assert.equal(isStaticElf(join(dir, "text")), false);
268 } finally {
269 rmSync(dir, { recursive: true, force: true });
270 }
271});
272
273test("path dependencies agree with Cargo's own resolved graph", (t) => {
274 let full;
275 try {
276 full = JSON.parse(execFileSync("cargo", ["metadata", "--format-version", "1", "--offline"], { cwd: ROOT, encoding: "utf8", maxBuffer: 256 << 20 }));
277 } catch {
278 t.skip("cargo metadata could not resolve offline");
279 return;
280 }
281 const cargo = cargoWorkspace(ROOT);
282 const dirOf = new Map(full.packages.filter((p) => p.source === null).map((p) => [p.id, p.manifest_path]));
283 const nodes = new Map(full.resolve.nodes.map((n) => [n.id, n]));
284 for (const u of stack.units.filter((u) => u.crate)) {
285 const root = full.packages.find((p) => p.name === u.crate).id;
286 const seen = new Set();
287 const stackIds = [root];
288 while (stackIds.length) {
289 const id = stackIds.pop();
290 for (const dep of nodes.get(id).deps) {
291 if (!dep.dep_kinds.some((k) => k.kind !== "dev")) continue;
292 if (dirOf.has(dep.pkg) && !seen.has(dep.pkg)) {
293 seen.add(dep.pkg);
294 stackIds.push(dep.pkg);
295 }
296 }
297 }
298 const names = [...seen].map((id) => full.packages.find((p) => p.id === id).name);
299 const dirs = names.map((name) => cargo.get(name).dir).sort();
300 assert.deepEqual(dirs, u.dependsOn.filter((d) => d.startsWith("crates/")).sort(), u.id);
301 }
302});
303
304test("every import that leaves a unit's folder is covered by its dependencies or inputs", () => {
305 for (const u of stack.units) {
306 for (const { file, target } of outsideImports(ROOT, u)) {
307 const covered = u.dependsOn.some((dir) => target.startsWith(`${dir}/`)) || u.inputs.some((input) => target === input || target.startsWith(input.replace(/\.ts$/, "")));
308 assert.ok(covered, `${file} imports ${target}, which ${u.id}'s manifest entry does not name`);
309 }
310 }
311});
312
313// ── What a change touches ─────────────────────────────────────────────────
314
315const ids = (units, files) => units.filter((u) => touches(u, files)).map((u) => u.id);
316
317test("a shared crate's change reaches every unit built from it, and no other", () => {
318 assert.deepEqual(ids(stack.units, ["crates/scan/src/lib.rs"]), ["repos", "security", "runner"]);
319 assert.deepEqual(ids(stack.units, ["crates/secrets/src/lib.rs"]), ["identity", "repos", "integrations", "webhooks", "actions"]);
320 const kit = ids(stack.units, ["crates/kit/src/lib.rs"]);
321 assert.deepEqual(kit, stack.units.filter((u) => u.kind === "rust-worker").map((u) => u.id));
322 assert.deepEqual(ids(stack.units, ["crates/runner/src/main.rs"]), ["runner"]);
323});
324
325test("a shared package's change reaches what imports it", () => {
326 assert.deepEqual(ids(stack.units, ["packages/theme/tokens.css"]), ["status", "web", "sudo", "docs"]);
327 assert.ok(ids(stack.units, ["packages/contracts/src/index.ts"]).includes("og"));
328 assert.ok(!ids(stack.units, ["packages/contracts/src/index.ts"]).includes("events"));
329});
330
331test("own folders, declared inputs and root files", () => {
332 assert.deepEqual(ids(stack.units, ["services/pages/src/index.ts"]), ["pages"]);
333 assert.deepEqual(ids(stack.units, ["apps/web/app/lib/roadmap.ts"]), ["og", "web"]);
334 assert.deepEqual(ids(stack.units, ["docs/PLAN.md", "README.md", "deploy/stack.jsonc"]), []);
335 assert.deepEqual(ids(stack.units, ["scripts/build-rust-worker.mjs"]), stack.units.filter((u) => u.kind === "rust-worker").map((u) => u.id));
336 // services/events is not a prefix of services/eventsx.
337 assert.equal(touches(unit("events"), ["services/eventsx/a.rs"]), null);
338});
339
340// ── Lockfiles ─────────────────────────────────────────────────────────────
341
342const lock = (sha2) => `version = 4
343
344[[package]]
345name = "g1t-events"
346version = "0.1.0"
347dependencies = [
348 "g1t-kit",
349]
350
351[[package]]
352name = "g1t-kit"
353version = "0.1.0"
354dependencies = [
355 "serde",
356]
357
358[[package]]
359name = "g1t-webhooks"
360version = "0.1.0"
361dependencies = [
362 "g1t-kit",
363 "g1t-secrets",
364]
365
366[[package]]
367name = "g1t-secrets"
368version = "0.1.0"
369dependencies = [
370 "sha2 ${sha2}",
371]
372
373[[package]]
374name = "serde"
375version = "1.0.0"
376source = "registry+https://github.com/rust-lang/crates.io-index"
377
378[[package]]
379name = "sha2"
380version = "${sha2}"
381source = "registry+https://github.com/rust-lang/crates.io-index"
382`;
383
384test("a Cargo.lock change reaches only crates that use what changed", () => {
385 const before = parseCargoLock(lock("0.10.8"));
386 const after = parseCargoLock(lock("0.10.9"));
387 const names = changedNames(before, after);
388 assert.deepEqual([...names], ["sha2"]);
389 assert.ok(reaches(after, ["g1t-webhooks"], names));
390 assert.ok(!reaches(after, ["g1t-events"], names));
391});
392
393test("a package-lock change reaches through workspace links", () => {
394 const make = (version) =>
395 JSON.stringify({
396 lockfileVersion: 3,
397 packages: {
398 "": { devDependencies: { wrangler: "^4" } },
399 "apps/web": { dependencies: { "@g1t/theme": "*", react: "^19" } },
400 "services/pages": { dependencies: {} },
401 "packages/theme": { dependencies: { fontkit: "^1" } },
402 "node_modules/@g1t/theme": { resolved: "packages/theme", link: true },
403 "node_modules/react": { version: "19.0.0" },
404 "node_modules/fontkit": { version },
405 "node_modules/wrangler": { version: "4.1.0" },
406 },
407 });
408 const before = parseNpmLock(make("1.0.0"));
409 const after = parseNpmLock(make("1.0.1"));
410 const names = changedNames(before, after);
411 assert.deepEqual([...names], ["fontkit"]);
412 assert.ok(reaches(after, ["apps/web", ""], names));
413 assert.ok(!reaches(after, ["services/pages", ""], names));
414});
415
416// ── Deciding ──────────────────────────────────────────────────────────────
417
418const HEAD = "a".repeat(40);
419const OLD = "b".repeat(40);
420const fakeGit = (files, { has = true, locks = {} } = {}) => ({
421 has: () => has,
422 changed: () => files,
423 show: (sha, path) => locks[`${sha}:${path}`] ?? "",
424});
425
426test("decide: changed units deploy, others wait, unknown ones deploy", () => {
427 const units = ["events", "repos", "pages", "web"].map(unit);
428 const live = { events: { sha: OLD }, repos: { sha: OLD }, pages: { sha: HEAD }, web: { sha: null, why: "never deployed" } };
429 const decisions = decide(units, { live, head: HEAD, gitApi: fakeGit(["crates/scan/src/lib.rs"]) });
430 const by = Object.fromEntries(decisions.map((d) => [d.unit.id, d]));
431 assert.equal(by.events.deploy, false);
432 assert.equal(by.events.reason, "nothing it is built from changed");
433 assert.equal(by.repos.deploy, true);
434 assert.match(by.repos.reason, /crates\/scan\/src\/lib.rs via crates\/scan/);
435 assert.equal(by.pages.deploy, false);
436 assert.equal(by.pages.reason, "up to date");
437 assert.equal(by.web.deploy, true);
438 assert.match(by.web.reason, /never deployed/);
439});
440
441test("decide: --force deploys unchanged units; a commit missing from history deploys", () => {
442 const forced = decide([unit("events")], { live: { events: { sha: HEAD } }, head: HEAD, force: true, gitApi: fakeGit([]) });
443 assert.equal(forced[0].deploy, true);
444 const shallow = decide([unit("events")], { live: { events: { sha: OLD } }, head: HEAD, gitApi: fakeGit([], { has: false }) });
445 assert.equal(shallow[0].deploy, true);
446 assert.match(shallow[0].reason, /does not have/);
447});
448
449test("decide: Cargo.lock counts only where it reaches", () => {
450 const locks = { [`${OLD}:Cargo.lock`]: lock("0.10.8"), [`${HEAD}:Cargo.lock`]: lock("0.10.9") };
451 const units = [unit("events"), unit("webhooks")];
452 const live = { events: { sha: OLD }, webhooks: { sha: OLD } };
453 const decisions = decide(units, { live, head: HEAD, gitApi: fakeGit(["Cargo.lock"], { locks }) });
454 assert.deepEqual(decisions.map((d) => [d.unit.id, d.deploy]), [["events", false], ["webhooks", true]]);
455});
456
457test("decide: the runner's image rebuilds only when what it is built from changed", () => {
458 const live = { runner: { sha: OLD } };
459 const code = decide([unit("runner")], { live, head: HEAD, gitApi: fakeGit(["services/runner/src/index.ts"]) });
460 assert.deepEqual([code[0].deploy, code[0].image], [true, false]);
461 const image = decide([unit("runner")], { live, head: HEAD, gitApi: fakeGit(["crates/runner/src/main.rs"]) });
462 assert.deepEqual([image[0].deploy, image[0].image], [true, true]);
463});
464
465test("the plan as data: migrations, and each stage's units in jobs that share a build", () => {
466 const units = ["events", "repos", "projects", "api", "web", "docs"].map(unit);
467 const decisions = units.map((u) => ({ unit: u, deploy: true, reason: "x", since: null, image: false }));
468 const data = planJson(stack, decisions, { events: { pending: ["0003_x.sql"] }, repos: { pending: [] } }, HEAD);
469 assert.deepEqual(data.migrations, [{ unit: "events", database: "g1t-events", pending: ["0003_x.sql"] }]);
470 assert.deepEqual(data.stages.core.jobs, [
471 { group: "rust", units: "events,repos", rust: true, image: false },
472 { group: "ts", units: "projects", rust: false, image: false },
473 ]);
474 assert.deepEqual(data.stages.edge.jobs, [{ group: "rust", units: "api", rust: true, image: false }]);
475 assert.deepEqual(data.stages.front.jobs, [
476 { group: "web", units: "web", rust: false, image: false },
477 { group: "docs", units: "docs", rust: false, image: false },
478 ]);
479 assert.deepEqual(data.stage_order, ["core", "edge", "front"]);
480 assert.deepEqual(buildGroups([]), []);
481 // Eleven Rust workers go to three jobs; a unit whose image rebuilds gets its own.
482 const core = stack.units.filter((u) => u.stage === "core");
483 const jobs = buildGroups(core, ["runner"]);
484 assert.deepEqual(jobs.filter((j) => j.rust).map((j) => j.units.split(",").length), [4, 4, 3]);
485 assert.ok(jobs.some((j) => j.group === "runner-image" && j.units === "runner" && j.image && !j.rust));
486 assert.ok(!jobs.find((j) => j.group === "ts").units.includes("runner"));
487});
488
489test("units are picked by short name, folder or Worker name", () => {
490 assert.deepEqual(pick(stack, ["billing,services/web".replace("services/web", "apps/web"), "g1t-api"]).map((u) => u.id), ["billing", "web", "api"]);
491 assert.throws(() => pick(stack, ["nope"]), /No unit called nope/);
492});
493
494test("a CI job installs only what its units need", () => {
495 const npm = npmWorkspace();
496 assert.deepEqual(npmCiArgs([unit("events"), unit("repos")], npm), ["ci", "--no-audit", "--no-fund", "--workspaces=false"]);
497 assert.deepEqual(npmCiArgs([unit("events"), unit("status")], npm), [
498 "ci", "--no-audit", "--no-fund", "--include-workspace-root",
499 "-w", "@g1t/contracts", "-w", "@g1t/status", "-w", "@g1t/theme",
500 ]);
501});
502
503// ── Cloudflare's answers ──────────────────────────────────────────────────
504
505const version = (id, number, message, triggered = "deployment") => ({
506 id,
507 number,
508 metadata: { created_on: "2026-10-05T00:00:00Z", author_email: "a@b" },
509 annotations: { "workers/triggered_by": triggered, ...(message ? { "workers/message": message } : {}) },
510});
511
512test("a deploy is annotated with its commit, and read back", () => {
513 const { message, tag } = annotation(HEAD, "A subject ".repeat(20));
514 assert.ok(message.length <= 100);
515 assert.equal(commitFrom(message), HEAD);
516 assert.equal(tag, `g1t-${HEAD.slice(0, 12)}`);
517 assert.equal(commitFrom(message.replace("g1t-deploy", "g1t-deploy-dirty")), null);
518 assert.equal(commitFrom("deployed by hand"), null);
519});
520
521test("the live commit: the live version's, looking through secret changes", () => {
522 const versions = [version("v1", 1, annotation(OLD).message), version("v2", 2, null, "secret"), version("v3", 3, null, "version_upload")];
523 const status = (id) => ({ versions: [{ version_id: id, percentage: 100 }] });
524 assert.equal(liveCommit(status("v1"), versions).sha, OLD);
525 assert.equal(liveCommit(status("v2"), versions).sha, OLD);
526 assert.equal(liveCommit(status("v3"), versions).sha, null);
527 assert.match(liveCommit(status("v9"), versions).why, /not among/);
528 const split = liveCommit({ versions: [{ version_id: "v1", percentage: 10 }, { version_id: "v2", percentage: 90 }] }, versions);
529 assert.equal(split.sha, OLD);
530 assert.equal(split.split, true);
531});
532
533test("Wrangler's output: pending migrations and the version a deploy made", () => {
534 const pending = `
535 ⛅️ wrangler 4.146.0
536Resource location: remote
537Migrations to be applied:
538┌──────────────────────┐
539│ Name │
540├──────────────────────┤
541│ 0021_confidence.sql │
542├──────────────────────┤
543│ 0022_more.sql │
544└──────────────────────┘`;
545 assert.deepEqual(pendingFrom(pending), ["0021_confidence.sql", "0022_more.sql"]);
546 assert.deepEqual(pendingFrom("Resource location: remote\n\n✅ No migrations to apply!"), []);
547 assert.equal(versionFrom("Deployed g1t-events triggers\nCurrent Version ID: 2c7fc93a-82d9-4850-8a77-ba887d157a4f\n"), "2c7fc93a-82d9-4850-8a77-ba887d157a4f");
548});
549
550// Cloudflare's REST answers, as the API sends them (Wrangler's --json
551// prints the first deployment, and the versions' items).
552const AUTH = { token: "t", account: "acct" };
553const ok = (result) => ({ success: true, errors: [], messages: [], result });
554const refused = (code, message) => ({ success: false, errors: [{ code, message }], messages: [], result: null });
555/** A fetch that answers by path: { "GET /path": [status, body] }. */
556function fakeFetch(answers, calls = []) {
557 return async (url, init) => {
558 const path = url.replace("https://api.cloudflare.com/client/v4", "");
559 calls.push({ path, init });
560 const found = answers[`${init.method} ${path}`];
561 if (!found) throw new Error(`unexpected ${init.method} ${path}`);
562 const [status, body] = found;
563 return { status, text: async () => (typeof body === "string" ? body : JSON.stringify(body)) };
564 };
565}
566const SCRIPT = "/accounts/acct/workers/scripts/g1t-events";
567const deploymentsAnswer = (id) =>
568 ok({
569 deployments: [
570 { id: "d2", source: "wrangler", strategy: "percentage", versions: [{ version_id: id, percentage: 100 }], annotations: { "workers/triggered_by": "deployment" } },
571 { id: "d1", source: "wrangler", strategy: "percentage", versions: [{ version_id: "v1", percentage: 100 }] },
572 ],
573 });
574const versionsAnswer = ok({ items: [version("v1", 1, annotation(OLD).message), version("v2", 2, null, "secret")] });
575
576test("the API's answers: the live commit as Wrangler's would give it", async () => {
577 const calls = [];
578 const fetchImpl = fakeFetch({ [`GET ${SCRIPT}/deployments`]: [200, deploymentsAnswer("v2")], [`GET ${SCRIPT}/versions?deployable=true`]: [200, versionsAnswer] }, calls);
579 const found = await readLive(unit("events"), { auth: AUTH, fetchImpl });
580 assert.equal(found.sha, OLD);
581 assert.equal(found.version, "v2");
582 assert.equal(found.at, "2026-10-05T00:00:00Z");
583 assert.equal(calls[0].init.headers.authorization, "Bearer t");
584 // The same as liveCommit over what Wrangler printed.
585 assert.deepEqual(liveFromApi("w", deploymentsAnswer("v2").result, versionsAnswer.result), liveCommit(deploymentsAnswer("v2").result.deployments[0], versionsAnswer.result.items));
586 // Versions that cannot be read: the live one is not among them.
587 assert.match(liveFromApi("w", deploymentsAnswer("v2").result, null).why, /not among/);
588 // No deployment at all is an error, as `deployments status` made it.
589 assert.match(liveFromApi("w", { deployments: [] }, versionsAnswer.result).error, /no deployments/);
590});
591
592test("the API's answers: a Worker never deployed, and a refusal, never throw", async () => {
593 const missing = fakeFetch({
594 [`GET ${SCRIPT}/deployments`]: [404, refused(10007, "workers.api.error.script_not_found")],
595 [`GET ${SCRIPT}/versions?deployable=true`]: [404, refused(10007, "workers.api.error.script_not_found")],
596 });
597 assert.deepEqual(await readLive(unit("events"), { auth: AUTH, fetchImpl: missing }), { sha: null, missing: true, why: "never deployed" });
598 const denied = fakeFetch({
599 [`GET ${SCRIPT}/deployments`]: [400, refused(10000, "Authentication error")],
600 [`GET ${SCRIPT}/versions?deployable=true`]: [400, refused(10000, "Authentication error")],
601 });
602 const found = await readLive(unit("events"), { auth: AUTH, fetchImpl: denied });
603 assert.equal(found.sha, null);
604 assert.match(found.error, /Authentication error \(10000\)/);
605 const broken = async () => {
606 throw new Error("connect ECONNREFUSED");
607 };
608 const offline = await readLive(unit("events"), { auth: AUTH, fetchImpl: broken });
609 assert.match(offline.error, /ECONNREFUSED/);
610 const garbled = fakeFetch({ [`GET ${SCRIPT}/deployments`]: [200, "<html>"], [`GET ${SCRIPT}/versions?deployable=true`]: [200, versionsAnswer] });
611 assert.match((await readLive(unit("events"), { auth: AUTH, fetchImpl: garbled })).error, /<html>/);
612});
613
614test("the API is used only with the token Wrangler would be given", () => {
615 assert.equal(apiAuth({ CLOUDFLARE_API_TOKEN: "shell" }), null);
616 assert.deepEqual(apiAuth({ CI: "true", CLOUDFLARE_API_TOKEN: "ci", CLOUDFLARE_ACCOUNT_ID: "a" }), { token: "ci", account: "a" });
617 assert.equal(apiAuth({ CLOUDFLARE_DEPLOY_TOKEN: "mine" }).token, "mine");
618 assert.equal(apiAuth({ CLOUDFLARE_DEPLOY_TOKEN: "mine" }).account, "1e6f2cffa3f445920836e8ebe446bb58");
619});
620
621test("pending migrations: the folder's files less the names in d1_migrations", async () => {
622 const events = unit("events");
623 const db = databaseOf(events);
624 assert.equal(db.id, events.config.d1_databases[0].database_id);
625 assert.equal(db.table, "d1_migrations");
626 const files = migrationFiles(join(ROOT, db.dir));
627 assert.ok(files.length > 2 && files.every((f) => f.endsWith(".sql")));
628 assert.deepEqual(files, [...files].sort());
629
630 assert.deepEqual(pendingAgainst(["0001_a.sql", "0002_b.sql", "0003_c.sql"], [{ results: [{ name: "0001_a.sql" }, { name: "0002_b.sql" }], success: true, meta: {} }]), ["0003_c.sql"]);
631 assert.deepEqual(pendingAgainst(["0001_a.sql"], [{ results: [], success: true }]), ["0001_a.sql"]);
632
633 const query = `POST /accounts/acct/d1/database/${db.id}/query`;
634 const calls = [];
635 const applied = files.slice(0, -1).map((name, i) => ({ name, id: i + 1 }));
636 const found = await pendingMigrations(events, { auth: AUTH, fetchImpl: fakeFetch({ [query]: [200, ok([{ results: applied, success: true, meta: {} }])] }, calls) });
637 assert.deepEqual(found, { pending: files.slice(-1) });
638 assert.match(JSON.parse(calls[0].init.body).sql, /^SELECT name FROM "d1_migrations"/);
639 const upToDate = await pendingMigrations(events, { auth: AUTH, fetchImpl: fakeFetch({ [query]: [200, ok([{ results: files.map((name) => ({ name })) }])] }) });
640 assert.deepEqual(upToDate, { pending: [] });
641 // A database never migrated has no table: everything is pending.
642 const fresh = await pendingMigrations(events, { auth: AUTH, fetchImpl: fakeFetch({ [query]: [400, refused(7500, "no such table: d1_migrations: SQLITE_ERROR")] }) });
643 assert.deepEqual(fresh, { pending: files });
644 const denied = await pendingMigrations(events, { auth: AUTH, fetchImpl: fakeFetch({ [query]: [400, refused(10000, "Authentication error")] }) });
645 assert.match(denied.error, /Authentication error/);
646});
647
648test("the pool runs everything, no more than its limit at once", async () => {
649 let running = 0;
650 let most = 0;
651 const out = await pool([1, 2, 3, 4, 5, 6, 7], 3, async (n) => {
652 running++;
653 most = Math.max(most, running);
654 await new Promise((resolve) => setTimeout(resolve, 5));
655 running--;
656 return n * 2;
657 });
658 assert.deepEqual(out, [2, 4, 6, 8, 10, 12, 14]);
659 assert.equal(most, 3);
660});
661
662// ── Everything else that reads the list ───────────────────────────────────
663
664test("self-hosting builds every Rust service the manifest says it runs", () => {
665 const dockerfile = readFileSync(join(ROOT, "deploy/self-host/Dockerfile"), "utf8");
666 const loops = [...dockerfile.matchAll(/for service in ([a-z ]+); do/g)].map((m) => m[1].trim().split(/\s+/).sort());
667 const wanted = stack.units.filter((u) => u.self_host === "run" && u.kind === "rust-worker").map((u) => u.path.split("/").pop()).sort();
668 assert.ok(loops.length >= 2);
669 for (const loop of loops) assert.deepEqual(loop, wanted);
670});
671
672test("docs/SELF_HOSTING.md's table names every unit", () => {
673 const doc = readFileSync(join(ROOT, "docs/SELF_HOSTING.md"), "utf8");
674 for (const u of stack.units) assert.ok(doc.includes(`| \`${u.path}\` |`), `${u.path} is missing from docs/SELF_HOSTING.md`);
675});
676
677test("resolveStack works on a manifest with no workspace crates or packages", () => {
678 const bare = resolveStack(loadStack(), { cargo: new Map(), npm: new Map() });
679 assert.deepEqual(bare.units.find((u) => u.id === "events").dependsOn, []);
680});
681
682test("decide: a commit older than what runs is never deployed by accident, even forced; --rollback means it", () => {
683 const newer = { has: () => true, changed: () => ["services/events/src/lib.rs"], show: () => "", isAncestor: (older, newer) => older === HEAD && newer === OLD };
684 const refused = decide([unit("events")], { live: { events: { sha: OLD } }, head: HEAD, force: true, gitApi: newer });
685 assert.equal(refused[0].deploy, false);
686 assert.match(refused[0].reason, /newer than this commit/);
687 const meant = decide([unit("events")], { live: { events: { sha: OLD } }, head: HEAD, rollback: true, gitApi: newer });
688 assert.equal(meant[0].deploy, true);
689 assert.match(meant[0].reason, /rolling back/);
690});
691
692test("a deploy by hand reports to the repository on g1t, and a workflow's does not", async () => {
693 const { g1tRemote, inWorkflow, deployToken, reportDeployment } = await import("./report.mjs");
694 assert.deepEqual(g1tRemote(["git@github.com:flagon-io/g1t.git", "https://g1t.sh/flagon-io/g1t.git"]), { api: "https://api.g1t.sh", repo: "flagon-io/g1t" });
695 assert.equal(g1tRemote(["git@github.com:flagon-io/g1t.git"]), null);
696 assert.equal(inWorkflow({ GITHUB_ACTIONS: "true" }), true);
697 assert.equal(inWorkflow({}), false);
698 assert.equal(deployToken({ G1T_DEPLOY_TOKEN: " g1t_x \n" }, "/nowhere"), "g1t_x");
699 assert.equal(deployToken({}, "/nowhere"), null);
700 let called = false;
701 const settle = await reportDeployment({ head: "abc", subject: "s", units: ["web"], log: () => {}, env: { GITHUB_ACTIONS: "true", G1T_DEPLOY_TOKEN: "t" }, fetchImpl: () => { called = true; } });
702 assert.equal(settle, null);
703 assert.equal(called, false);
704});