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