Skip to content
794 linesCodeBlameRaw

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

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