Skip to content

g1t/scripts/deploy/deploy.test.mjs

593 lines28,318 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

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

This file's history is long; its oldest lines are credited to the oldest commit read.