| 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 { |
| 28 | annotation, |
| 29 | apiAuth, |
| 30 | commitFrom, |
| 31 | databaseOf, |
| 32 | liveCommit, |
| 33 | liveFromApi, |
| 34 | migrationFiles, |
| 35 | pendingAgainst, |
| 36 | pendingFrom, |
| 37 | pendingMigrations, |
| 38 | readLive, |
| 39 | retryableDeploy, |
| 40 | versionFrom, |
| 41 | wranglerError, |
| 42 | } from "./cloudflare.mjs"; |
| 43 | import { changedNames, parseCargoLock, parseNpmLock, reaches } from "./lockfiles.mjs"; |
| 44 | import { decide, git, planJson, pool } from "./plan.mjs"; |
| 45 | import { |
| 46 | ROOT, |
| 47 | buildGroups, |
| 48 | cargoWorkspace, |
| 49 | findWranglerConfigs, |
| 50 | loadStack, |
| 51 | npmCiArgs, |
| 52 | containersRollout, |
| 53 | npmWorkspace, |
| 54 | outsideImports, |
| 55 | parseJsonc, |
| 56 | pick, |
| 57 | problems, |
| 58 | resolveStack, |
| 59 | resolvedStack, |
| 60 | testOnlySource, |
| 61 | touches, |
| 62 | touchesBase, |
| 63 | touchesImage, |
| 64 | waves, |
| 65 | } from "./stack.mjs"; |
| 66 | |
| 67 | const stack = resolvedStack(); |
| 68 | const unit = (id) => stack.units.find((u) => u.id === id); |
| 69 | |
| 70 | // ── The manifest ────────────────────────────────────────────────────────── |
| 71 | |
| 72 | test("the manifest matches every wrangler config in the repository", () => { |
| 73 | assert.deepEqual(problems(stack, findWranglerConfigs()), []); |
| 74 | }); |
| 75 | |
| 76 | test("every wrangler.jsonc is found, and only checked-in ones", () => { |
| 77 | const configs = findWranglerConfigs(); |
| 78 | assert.ok(configs.includes("services/events/wrangler.jsonc")); |
| 79 | assert.ok(configs.includes("apps/web/wrangler.jsonc")); |
| 80 | assert.ok(!configs.some((c) => c.includes("/build/")), "build output is not a unit"); |
| 81 | assert.equal(configs.length, stack.units.length); |
| 82 | }); |
| 83 | |
| 84 | test("problems are found: an unlisted config, a later-stage binding, a wrong database, an unnamed KV", () => { |
| 85 | const broken = loadStack(); |
| 86 | const events = broken.units.find((u) => u.id === "events"); |
| 87 | events.stage = "front"; |
| 88 | const identity = broken.units.find((u) => u.id === "identity"); |
| 89 | identity.d1 = { database: "g1t-identity", migrations: "migrations" }; |
| 90 | broken.resources = { kv: {} }; |
| 91 | const found = problems(broken, [...findWranglerConfigs(), "services/new/wrangler.jsonc"]); |
| 92 | assert.ok(found.some((p) => p.includes("services/new/wrangler.jsonc is not in"))); |
| 93 | assert.ok(found.some((p) => p.includes("binds to events (front), which ships after it"))); |
| 94 | assert.ok(found.some((p) => p.startsWith("Unit identity: d1 is"))); |
| 95 | assert.ok(found.some((p) => p.includes("has no name under resources.kv"))); |
| 96 | }); |
| 97 | |
| 98 | test("stages follow bindings: nothing binds to a unit that ships after it", () => { |
| 99 | const order = stack.stages; |
| 100 | for (const u of stack.units) { |
| 101 | for (const target of u.bindsTo) { |
| 102 | const other = stack.units.find((o) => o.worker === target); |
| 103 | assert.ok(order.indexOf(other.stage) <= order.indexOf(u.stage), `${u.id} -> ${other.id}`); |
| 104 | } |
| 105 | } |
| 106 | }); |
| 107 | |
| 108 | test("inside a stage, a Worker that does not exist yet goes before those bound to it", () => { |
| 109 | const u = (id, worker, bindsTo = []) => ({ id, worker, bindsTo }); |
| 110 | const artifacts = u("artifacts", "g1t-artifacts", ["g1t-notify", "g1t-identity"]); |
| 111 | const notify = u("notify", "g1t-notify", ["g1t-artifacts", "g1t-identity"]); |
| 112 | const chat = u("chat", "g1t-chat", ["g1t-notify"]); |
| 113 | const ids = (list) => list.map((wave) => wave.map((x) => x.id)); |
| 114 | // Nothing new: one wave, as before. |
| 115 | assert.deepEqual(ids(waves([artifacts, notify, chat], () => false)), [["artifacts", "notify", "chat"]]); |
| 116 | // A renamed Worker: it first, then what binds to it. |
| 117 | assert.deepEqual(ids(waves([notify, chat, artifacts], (x) => x.id === "artifacts")), [["chat", "artifacts"], ["notify"]]); |
| 118 | // New Workers bound to each other: no order helps, so together. |
| 119 | assert.deepEqual(ids(waves([artifacts, notify], () => true)), [["artifacts", "notify"]]); |
| 120 | // This repository's chat unit binds to the notify Worker, in the same stage. |
| 121 | const real = (id) => stack.units.find((x) => x.id === id); |
| 122 | assert.equal(real("chat").stage, real("notify").stage); |
| 123 | assert.deepEqual(ids(waves([real("chat"), real("notify")], (x) => x.id === "notify")), [["notify"], ["chat"]]); |
| 124 | }); |
| 125 | |
| 126 | test("Rust workers build with the shared script and the same wasm-opt level", () => { |
| 127 | for (const u of stack.units.filter((u) => u.kind === "rust-worker")) { |
| 128 | assert.equal(u.config.build.command, "node ../../scripts/build-rust-worker.mjs", u.id); |
| 129 | const toml = readFileSync(join(ROOT, u.path, "Cargo.toml"), "utf8"); |
| 130 | assert.match(toml, /\[package\.metadata\.wasm-pack\.profile\.release\]\s*\nwasm-opt = \["-O1"\]/, u.id); |
| 131 | } |
| 132 | }); |
| 133 | |
| 134 | // ── What each unit is built from ────────────────────────────────────────── |
| 135 | |
| 136 | test("shared crates and packages are read from workspace metadata", () => { |
| 137 | assert.deepEqual(unit("events").dependsOn, ["crates/contracts", "crates/kit"]); |
| 138 | assert.deepEqual(unit("repos").dependsOn, ["crates/blobstore", "crates/contracts", "crates/kit", "crates/rules", "crates/scan", "crates/secrets"]); |
| 139 | assert.ok(unit("work").dependsOn.includes("crates/rules")); |
| 140 | assert.ok(unit("actions").dependsOn.includes("crates/actions")); |
| 141 | assert.ok(!unit("events").dependsOn.includes("crates/scan")); |
| 142 | assert.deepEqual(unit("web").dependsOn, ["packages/contracts", "packages/theme"]); |
| 143 | assert.deepEqual(unit("projects").dependsOn, ["packages/contracts"]); |
| 144 | assert.deepEqual(unit("pages").dependsOn, []); |
| 145 | assert.equal(unit("events").crate, "g1t-events"); |
| 146 | assert.equal(unit("web").pkg, "@g1t/web"); |
| 147 | }); |
| 148 | |
| 149 | test("the runner's image is built from the runner crate and what it uses, on the base its lock names", () => { |
| 150 | const runner = unit("runner"); |
| 151 | // The runner bumps lockfiles with the scanner's lockfile parser (security updates). |
| 152 | assert.deepEqual(runner.image.dirs, ["crates/actions", "crates/runner", "crates/scan"]); |
| 153 | assert.deepEqual(runner.image.baseDirs, ["services/runner/base"]); |
| 154 | assert.ok(runner.dependsOn.includes("crates/runner")); |
| 155 | assert.ok(touchesImage(runner, ["crates/actions/src/expr.rs"])); |
| 156 | assert.ok(touchesImage(runner, ["services/runner/Dockerfile"])); |
| 157 | assert.ok(touchesImage(runner, ["services/runner/base.json"])); |
| 158 | assert.ok(touchesImage(runner, ["scripts/build-runner.mjs"])); |
| 159 | assert.ok(!touchesImage(runner, ["services/runner/src/index.ts"])); |
| 160 | // The base's Dockerfile reaches the image only through a new lock. |
| 161 | assert.ok(!touchesImage(runner, ["services/runner/base/Dockerfile"])); |
| 162 | assert.ok(touchesBase(runner, ["services/runner/base/Dockerfile"])); |
| 163 | assert.ok(!touchesBase(unit("events"), ["services/runner/base/Dockerfile"])); |
| 164 | }); |
| 165 | |
| 166 | // ── The runner's images ─────────────────────────────────────────────────── |
| 167 | |
| 168 | test("services/runner/base.json records the base its folder builds", () => { |
| 169 | const runner = unit("runner"); |
| 170 | const lock = readBaseLock(runner); |
| 171 | assert.ok(lock, "services/runner/base.json is missing: node scripts/deploy.mjs build-base"); |
| 172 | assert.equal( |
| 173 | lock.inputs, |
| 174 | baseInputs(runner), |
| 175 | "services/runner/base changed since base.json was written: node scripts/deploy.mjs build-base, and commit base.json", |
| 176 | ); |
| 177 | assert.match(lock.image, /^registry\.cloudflare\.com\/[0-9a-f]{32}\/g1t-runner:base-\d{8}-[0-9a-f]{12}$/); |
| 178 | assert.ok(lock.image.endsWith(lock.inputs.slice(0, 12))); |
| 179 | assert.equal(baseState(runner).current, true); |
| 180 | }); |
| 181 | |
| 182 | test("an image's hash ignores line endings, and its tags say what they are", () => { |
| 183 | const files = { "a.txt": "one\r\ntwo\r\n", "b.txt": "x" }; |
| 184 | const lf = { "a.txt": "one\ntwo\n", "b.txt": "x" }; |
| 185 | const hash = (set) => contentHash(Object.keys(set), "/", (file) => Buffer.from(set[file])); |
| 186 | assert.equal(hash(files), hash(lf)); |
| 187 | assert.notEqual(hash(lf), hash({ ...lf, "b.txt": "y" })); |
| 188 | assert.equal(baseTag("0123456789abcdef".repeat(4), new Date("2026-10-06T12:00:00Z")), "base-20261006-0123456789ab"); |
| 189 | const runner = unit("runner"); |
| 190 | assert.match(runnerTag(runner), /^[0-9a-f]{16}$/); |
| 191 | assert.equal(runnerTag(runner), runnerTag(runner)); |
| 192 | assert.equal(runnerRef(runner, ROOT, "a".repeat(32)), `registry.cloudflare.com/${"a".repeat(32)}/g1t-runner:${runnerTag(runner)}`); |
| 193 | }); |
| 194 | |
| 195 | test("only the lockfile entries the runner is built from name its image", () => { |
| 196 | const lock = (wasm) => `[[package]] |
| 197 | name = "g1t-runner" |
| 198 | version = "0.1.0" |
| 199 | dependencies = [ |
| 200 | "ureq", |
| 201 | ] |
| 202 | |
| 203 | [[package]] |
| 204 | name = "ureq" |
| 205 | version = "2.12.1" |
| 206 | |
| 207 | [[package]] |
| 208 | name = "wasm-bindgen" |
| 209 | version = "${wasm}" |
| 210 | `; |
| 211 | assert.equal(lockFor(lock("0.2.100"), "g1t-runner"), lockFor(lock("0.2.101"), "g1t-runner")); |
| 212 | assert.ok(lockFor(lock("0.2.100"), "g1t-runner").includes("ureq")); |
| 213 | assert.notEqual(lockFor(lock("0.2.100"), "g1t-runner"), lockFor(lock("0.2.100").replace("2.12.1", "2.12.2"), "g1t-runner")); |
| 214 | }); |
| 215 | |
| 216 | test("the runner's deploy config names its image by reference, beside its wrangler.jsonc", () => { |
| 217 | const runner = unit("runner"); |
| 218 | const ref = "registry.cloudflare.com/acct/g1t-runner:0123456789abcdef"; |
| 219 | const name = writeDeployConfig(runner, ref); |
| 220 | try { |
| 221 | assert.equal(name, DEPLOY_CONFIG); |
| 222 | const config = JSON.parse(readFileSync(join(ROOT, runner.path, DEPLOY_CONFIG), "utf8")); |
| 223 | assert.equal(config.name, "g1t-runner"); |
| 224 | assert.equal(config.main, "./src/index.ts"); |
| 225 | assert.ok(config.containers.length >= 1); |
| 226 | for (const container of config.containers) { |
| 227 | assert.equal(container.image, ref); |
| 228 | assert.equal(container.image_build_context, undefined); |
| 229 | } |
| 230 | // Every sandbox class shares the image; each has a Durable Object binding. |
| 231 | const classes = config.containers.map((c) => c.class_name).sort(); |
| 232 | assert.deepEqual(classes, config.durable_objects.bindings.map((b) => b.class_name).sort()); |
| 233 | // Generated, never committed, and not taken for a unit of its own. |
| 234 | assert.ok(readFileSync(join(ROOT, ".gitignore"), "utf8").includes("wrangler.deploy.json")); |
| 235 | assert.ok(!findWranglerConfigs().some((c) => c.endsWith(DEPLOY_CONFIG))); |
| 236 | } finally { |
| 237 | removeDeployConfig(runner); |
| 238 | } |
| 239 | assert.ok(!existsSync(join(ROOT, runner.path, DEPLOY_CONFIG))); |
| 240 | }); |
| 241 | |
| 242 | test("the registry is asked for an image's manifest, without Docker", async () => { |
| 243 | const asked = []; |
| 244 | const fetchImpl = async (url, init) => { |
| 245 | asked.push([url, init.method, init.headers.authorization]); |
| 246 | return { status: url.endsWith(":nope") || url.endsWith("/nope") ? 404 : 200, ok: !url.endsWith("/nope") }; |
| 247 | }; |
| 248 | const credentials = async () => ({ username: "v1", password: "secret" }); |
| 249 | assert.equal(await registryHas("registry.cloudflare.com/acct/g1t-runner:abc", { fetchImpl, credentials }), true); |
| 250 | assert.equal(await registryHas("registry.cloudflare.com/acct/g1t-runner:nope", { fetchImpl, credentials }), false); |
| 251 | assert.deepEqual(asked[0], [ |
| 252 | "https://registry.cloudflare.com/v2/acct/g1t-runner/manifests/abc", |
| 253 | "HEAD", |
| 254 | `Basic ${Buffer.from("v1:secret").toString("base64")}`, |
| 255 | ]); |
| 256 | await assert.rejects(registryHas("not-a-reference", { fetchImpl, credentials })); |
| 257 | }); |
| 258 | |
| 259 | test("a push counts only when it ends with a digest, and is tried again", async () => { |
| 260 | const digest = "sha256:" + "a".repeat(64); |
| 261 | assert.equal(pushedDigest({ code: 0, out: `base: digest: ${digest} size: 856` }), digest); |
| 262 | assert.equal(pushedDigest({ code: 0, out: "error from registry: blob unknown to registry" }), null); |
| 263 | assert.equal(pushedDigest({ code: 1, out: `digest: ${digest}` }), null); |
| 264 | assert.equal(pushedDigest({ code: 0, out: "Pushed" }), null); |
| 265 | const answers = [ |
| 266 | { code: 1, out: "error from registry: blob unknown to registry" }, |
| 267 | { code: 0, out: `x: digest: ${digest} size: 1` }, |
| 268 | ]; |
| 269 | assert.equal(await pushImage("r/x:y", { run: async () => answers.shift() }), digest); |
| 270 | await assert.rejects(pushImage("r/x:y", { attempts: 2, run: async () => ({ code: 0, out: "blob unknown" }) }), /docker push r\/x:y failed/); |
| 271 | }); |
| 272 | |
| 273 | test("a static Linux binary is told from a dynamic one", () => { |
| 274 | const dir = mkdtempSync(join(tmpdir(), "g1t-elf-")); |
| 275 | try { |
| 276 | const elf = (interp) => { |
| 277 | // 64-bit little-endian x86-64 ELF with one program header. |
| 278 | const bytes = Buffer.alloc(64 + 56); |
| 279 | bytes.writeUInt32BE(0x7f454c46, 0); |
| 280 | bytes[4] = 2; |
| 281 | bytes[5] = 1; |
| 282 | bytes.writeUInt16LE(0x3e, 18); |
| 283 | bytes.writeBigUInt64LE(64n, 32); |
| 284 | bytes.writeUInt16LE(56, 54); |
| 285 | bytes.writeUInt16LE(1, 56); |
| 286 | bytes.writeUInt32LE(interp ? 3 : 1, 64); |
| 287 | return bytes; |
| 288 | }; |
| 289 | writeFileSync(join(dir, "static"), elf(false)); |
| 290 | writeFileSync(join(dir, "dynamic"), elf(true)); |
| 291 | writeFileSync(join(dir, "text"), "#!/bin/sh\n"); |
| 292 | assert.equal(isStaticElf(join(dir, "static")), true); |
| 293 | assert.equal(isStaticElf(join(dir, "dynamic")), false); |
| 294 | assert.equal(isStaticElf(join(dir, "text")), false); |
| 295 | } finally { |
| 296 | rmSync(dir, { recursive: true, force: true }); |
| 297 | } |
| 298 | }); |
| 299 | |
| 300 | test("path dependencies agree with Cargo's own resolved graph", (t) => { |
| 301 | let full; |
| 302 | try { |
| 303 | full = JSON.parse(execFileSync("cargo", ["metadata", "--format-version", "1", "--offline"], { cwd: ROOT, encoding: "utf8", maxBuffer: 256 << 20 })); |
| 304 | } catch { |
| 305 | t.skip("cargo metadata could not resolve offline"); |
| 306 | return; |
| 307 | } |
| 308 | const cargo = cargoWorkspace(ROOT); |
| 309 | const dirOf = new Map(full.packages.filter((p) => p.source === null).map((p) => [p.id, p.manifest_path])); |
| 310 | const nodes = new Map(full.resolve.nodes.map((n) => [n.id, n])); |
| 311 | for (const u of stack.units.filter((u) => u.crate)) { |
| 312 | const root = full.packages.find((p) => p.name === u.crate).id; |
| 313 | const seen = new Set(); |
| 314 | const stackIds = [root]; |
| 315 | while (stackIds.length) { |
| 316 | const id = stackIds.pop(); |
| 317 | for (const dep of nodes.get(id).deps) { |
| 318 | if (!dep.dep_kinds.some((k) => k.kind !== "dev")) continue; |
| 319 | if (dirOf.has(dep.pkg) && !seen.has(dep.pkg)) { |
| 320 | seen.add(dep.pkg); |
| 321 | stackIds.push(dep.pkg); |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | const names = [...seen].map((id) => full.packages.find((p) => p.id === id).name); |
| 326 | const dirs = names.map((name) => cargo.get(name).dir).sort(); |
| 327 | assert.deepEqual(dirs, u.dependsOn.filter((d) => d.startsWith("crates/")).sort(), u.id); |
| 328 | } |
| 329 | }); |
| 330 | |
| 331 | test("every import that leaves a unit's folder is covered by its dependencies or inputs", () => { |
| 332 | for (const u of stack.units) { |
| 333 | for (const { file, target } of outsideImports(ROOT, u)) { |
| 334 | const covered = |
| 335 | u.dependsOn.some((dir) => target.startsWith(`${dir}/`)) || u.inputs.some((input) => target === input || target.startsWith(input.replace(/\.ts$/, ""))); |
| 336 | assert.ok(covered, `${file} imports ${target}, which ${u.id}'s manifest entry does not name`); |
| 337 | } |
| 338 | } |
| 339 | }); |
| 340 | |
| 341 | // ── What a change touches ───────────────────────────────────────────────── |
| 342 | |
| 343 | const ids = (units, files) => units.filter((u) => touches(u, files)).map((u) => u.id); |
| 344 | |
| 345 | test("a shared crate's change reaches every unit built from it, and no other", () => { |
| 346 | assert.deepEqual(ids(stack.units, ["crates/scan/src/lib.rs"]), ["repos", "work", "security", "runner"]); |
| 347 | assert.deepEqual(ids(stack.units, ["crates/secrets/src/lib.rs"]), ["identity", "repos", "billing", "integrations", "webhooks", "actions"]); |
| 348 | const kit = ids(stack.units, ["crates/kit/src/lib.rs"]); |
| 349 | assert.deepEqual( |
| 350 | kit, |
| 351 | stack.units.filter((u) => u.kind === "rust-worker").map((u) => u.id), |
| 352 | ); |
| 353 | assert.deepEqual(ids(stack.units, ["crates/runner/src/main.rs"]), ["runner"]); |
| 354 | }); |
| 355 | |
| 356 | test("a shared package's change reaches what imports it", () => { |
| 357 | assert.deepEqual(ids(stack.units, ["packages/theme/tokens.css"]), ["status", "web", "sudo", "docs"]); |
| 358 | assert.ok(ids(stack.units, ["packages/contracts/src/index.ts"]).includes("og")); |
| 359 | assert.ok(!ids(stack.units, ["packages/contracts/src/index.ts"]).includes("events")); |
| 360 | }); |
| 361 | |
| 362 | test("a crate's tests, benches and examples deploy nothing", () => { |
| 363 | // 0cdd221 changed only this file, and the plan sent three Rust Workers. |
| 364 | assert.deepEqual(ids(stack.units, ["crates/actions/tests/repository_workflows.rs"]), []); |
| 365 | assert.ok(!touchesImage(unit("runner"), ["crates/actions/tests/repository_workflows.rs"])); |
| 366 | assert.deepEqual(ids(stack.units, ["crates/kit/benches/wire.rs", "crates/scan/examples/scan.rs", "services/repos/tests/git.rs"]), []); |
| 367 | // Their sources still do, and a folder merely named like one. |
| 368 | assert.deepEqual(ids(stack.units, ["crates/actions/src/expr.rs"]), ["actions", "security", "runner"]); |
| 369 | assert.ok(touchesImage(unit("runner"), ["crates/actions/src/expr.rs"])); |
| 370 | assert.deepEqual(ids(stack.units, ["services/repos/src/tests/helpers.rs"]), ["repos"]); |
| 371 | assert.deepEqual(ids(stack.units, ["crates/kit/testsuite/a.rs"]), ids(stack.units, ["crates/kit/src/lib.rs"])); |
| 372 | // A unit that is not a crate keeps its whole folder. |
| 373 | assert.deepEqual(unit("web").crateDirs, []); |
| 374 | assert.deepEqual(unit("events").crateDirs, ["crates/contracts", "crates/kit", "services/events"]); |
| 375 | assert.ok(unit("runner").crateDirs.includes("crates/runner")); |
| 376 | }); |
| 377 | |
| 378 | /** Rust sources by path, as `testOnlySource` reads them. */ |
| 379 | const sources = (files) => ({ |
| 380 | read: (path) => files[path] ?? "", |
| 381 | list: (dir) => Object.keys(files).filter((path) => path.slice(0, path.lastIndexOf("/")) === dir), |
| 382 | }); |
| 383 | |
| 384 | test("a Rust file compiled only for tests is found from what declares it", () => { |
| 385 | const crate = ["crates/x"]; |
| 386 | const tree = sources({ |
| 387 | "crates/x/src/lib.rs": |
| 388 | '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', |
| 389 | "crates/x/src/api.rs": 'mod wire;\n#[cfg(test)]\n#[path = "api_tests.rs"]\nmod tests;\n', |
| 390 | "crates/x/src/api/wire.rs": "", |
| 391 | "crates/x/src/api_tests.rs": "use super::*;", |
| 392 | "crates/x/src/store/mod.rs": "#[cfg(test)]\nmod memory;\n", |
| 393 | "crates/x/src/store/memory.rs": "mod deep;", |
| 394 | "crates/x/src/store/memory/deep.rs": "", |
| 395 | "crates/x/src/tests.rs": "", |
| 396 | "crates/x/src/fixtures/mod.rs": "", |
| 397 | "crates/x/src/both.rs": "", |
| 398 | "crates/x/src/bin/tool.rs": "", |
| 399 | }); |
| 400 | const only = (file) => testOnlySource(file, crate, tree); |
| 401 | for (const file of [ |
| 402 | "crates/x/src/tests.rs", |
| 403 | "crates/x/src/fixtures/mod.rs", |
| 404 | "crates/x/src/api_tests.rs", |
| 405 | "crates/x/src/store/memory.rs", |
| 406 | "crates/x/src/store/memory/deep.rs", |
| 407 | ]) { |
| 408 | assert.ok(only(file), file); |
| 409 | } |
| 410 | // Built: roots, ordinary modules, a cfg that is not only test, a file |
| 411 | // nothing declares (new, or deleted), and files outside src or the crate. |
| 412 | for (const file of [ |
| 413 | "crates/x/src/lib.rs", |
| 414 | "crates/x/src/api.rs", |
| 415 | "crates/x/src/api/wire.rs", |
| 416 | "crates/x/src/store/mod.rs", |
| 417 | "crates/x/src/both.rs", |
| 418 | "crates/x/src/bin/tool.rs", |
| 419 | "crates/x/src/new.rs", |
| 420 | "crates/x/build.rs", |
| 421 | "crates/y/src/tests.rs", |
| 422 | "crates/x/src/notes.md", |
| 423 | ]) { |
| 424 | assert.ok(!only(file), file); |
| 425 | } |
| 426 | }); |
| 427 | |
| 428 | test("this repository's test-only sources are read from git", () => { |
| 429 | const head = git.head(); |
| 430 | const atHead = { read: (path) => git.show(head, path), list: (dir) => git.list(head, dir) }; |
| 431 | const only = (u, file) => testOnlySource(file, unit(u).crateDirs, atHead); |
| 432 | assert.ok(only("api", "apps/api/src/responses.rs")); |
| 433 | assert.ok(!only("billing", "services/billing/src/compute.rs")); |
| 434 | assert.ok(!only("billing", "services/billing/src/limits.rs")); |
| 435 | assert.ok(!only("api", "apps/api/src/toolkit.rs")); |
| 436 | }); |
| 437 | |
| 438 | test("decide: a change only to tests deploys nothing", () => { |
| 439 | const units = ["actions", "billing", "runner"].map(unit); |
| 440 | const live = { actions: { sha: OLD }, billing: { sha: OLD }, runner: { sha: OLD } }; |
| 441 | const files = { |
| 442 | [`${HEAD}:services/billing/src/compute.rs`]: '#[cfg(test)]\n#[path = "compute_tests.rs"]\nmod tests;\n', |
| 443 | [`${HEAD}:services/billing/src/lib.rs`]: "mod compute;\n", |
| 444 | }; |
| 445 | const gitApi = { |
| 446 | ...fakeGit(["crates/actions/tests/repository_workflows.rs", "services/billing/src/compute_tests.rs"]), |
| 447 | show: (sha, path) => files[`${sha}:${path}`] ?? "", |
| 448 | list: (sha, dir) => |
| 449 | Object.keys(files) |
| 450 | .map((k) => k.slice(sha.length + 1)) |
| 451 | .filter((p) => p.startsWith(`${dir}/`)) |
| 452 | .concat(dir === "services/billing/src" ? ["services/billing/src/compute_tests.rs"] : []), |
| 453 | }; |
| 454 | const decisions = decide(units, { live, head: HEAD, gitApi }); |
| 455 | assert.deepEqual( |
| 456 | decisions.map((d) => [d.unit.id, d.deploy, d.image]), |
| 457 | [ |
| 458 | ["actions", false, false], |
| 459 | ["billing", false, false], |
| 460 | ["runner", false, false], |
| 461 | ], |
| 462 | ); |
| 463 | // With a source that ships beside them, only that is listed. |
| 464 | const mixed = decide([unit("billing")], { |
| 465 | live, |
| 466 | head: HEAD, |
| 467 | gitApi: { ...gitApi, changed: () => ["services/billing/src/compute_tests.rs", "services/billing/src/compute.rs"] }, |
| 468 | }); |
| 469 | assert.deepEqual([mixed[0].deploy, mixed[0].files], [true, ["services/billing/src/compute.rs"]]); |
| 470 | }); |
| 471 | |
| 472 | test("own folders, declared inputs and root files", () => { |
| 473 | assert.deepEqual(ids(stack.units, ["services/pages/src/index.ts"]), ["pages"]); |
| 474 | assert.deepEqual(ids(stack.units, ["apps/web/app/lib/roadmap.ts"]), ["og", "web"]); |
| 475 | assert.deepEqual(ids(stack.units, ["LICENSE", "README.md", "deploy/stack.jsonc"]), []); |
| 476 | assert.deepEqual( |
| 477 | ids(stack.units, ["scripts/build-rust-worker.mjs"]), |
| 478 | stack.units.filter((u) => u.kind === "rust-worker").map((u) => u.id), |
| 479 | ); |
| 480 | // services/events is not a prefix of services/eventsx. |
| 481 | assert.equal(touches(unit("events"), ["services/eventsx/a.rs"]), null); |
| 482 | }); |
| 483 | |
| 484 | // ── Lockfiles ───────────────────────────────────────────────────────────── |
| 485 | |
| 486 | const lock = (sha2) => `version = 4 |
| 487 | |
| 488 | [[package]] |
| 489 | name = "g1t-events" |
| 490 | version = "0.1.0" |
| 491 | dependencies = [ |
| 492 | "g1t-kit", |
| 493 | ] |
| 494 | |
| 495 | [[package]] |
| 496 | name = "g1t-kit" |
| 497 | version = "0.1.0" |
| 498 | dependencies = [ |
| 499 | "serde", |
| 500 | ] |
| 501 | |
| 502 | [[package]] |
| 503 | name = "g1t-webhooks" |
| 504 | version = "0.1.0" |
| 505 | dependencies = [ |
| 506 | "g1t-kit", |
| 507 | "g1t-secrets", |
| 508 | ] |
| 509 | |
| 510 | [[package]] |
| 511 | name = "g1t-secrets" |
| 512 | version = "0.1.0" |
| 513 | dependencies = [ |
| 514 | "sha2 ${sha2}", |
| 515 | ] |
| 516 | |
| 517 | [[package]] |
| 518 | name = "serde" |
| 519 | version = "1.0.0" |
| 520 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 521 | |
| 522 | [[package]] |
| 523 | name = "sha2" |
| 524 | version = "${sha2}" |
| 525 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 526 | `; |
| 527 | |
| 528 | test("a Cargo.lock change reaches only crates that use what changed", () => { |
| 529 | const before = parseCargoLock(lock("0.10.8")); |
| 530 | const after = parseCargoLock(lock("0.10.9")); |
| 531 | const names = changedNames(before, after); |
| 532 | assert.deepEqual([...names], ["sha2"]); |
| 533 | assert.ok(reaches(after, ["g1t-webhooks"], names)); |
| 534 | assert.ok(!reaches(after, ["g1t-events"], names)); |
| 535 | }); |
| 536 | |
| 537 | test("a package-lock change reaches through workspace links", () => { |
| 538 | const make = (version) => |
| 539 | JSON.stringify({ |
| 540 | lockfileVersion: 3, |
| 541 | packages: { |
| 542 | "": { devDependencies: { wrangler: "^4" } }, |
| 543 | "apps/web": { dependencies: { "@g1t/theme": "*", react: "^19" } }, |
| 544 | "services/pages": { dependencies: {} }, |
| 545 | "packages/theme": { dependencies: { fontkit: "^1" } }, |
| 546 | "node_modules/@g1t/theme": { resolved: "packages/theme", link: true }, |
| 547 | "node_modules/react": { version: "19.0.0" }, |
| 548 | "node_modules/fontkit": { version }, |
| 549 | "node_modules/wrangler": { version: "4.1.0" }, |
| 550 | }, |
| 551 | }); |
| 552 | const before = parseNpmLock(make("1.0.0")); |
| 553 | const after = parseNpmLock(make("1.0.1")); |
| 554 | const names = changedNames(before, after); |
| 555 | assert.deepEqual([...names], ["fontkit"]); |
| 556 | assert.ok(reaches(after, ["apps/web", ""], names)); |
| 557 | assert.ok(!reaches(after, ["services/pages", ""], names)); |
| 558 | }); |
| 559 | |
| 560 | // ── Deciding ────────────────────────────────────────────────────────────── |
| 561 | |
| 562 | const HEAD = "a".repeat(40); |
| 563 | const OLD = "b".repeat(40); |
| 564 | const fakeGit = (files, { has = true, locks = {} } = {}) => ({ |
| 565 | has: () => has, |
| 566 | changed: () => files, |
| 567 | show: (sha, path) => locks[`${sha}:${path}`] ?? "", |
| 568 | }); |
| 569 | |
| 570 | test("decide: changed units deploy, others wait, unknown ones deploy", () => { |
| 571 | const units = ["events", "repos", "pages", "web"].map(unit); |
| 572 | const live = { events: { sha: OLD }, repos: { sha: OLD }, pages: { sha: HEAD }, web: { sha: null, why: "never deployed" } }; |
| 573 | const decisions = decide(units, { live, head: HEAD, gitApi: fakeGit(["crates/scan/src/lib.rs"]) }); |
| 574 | const by = Object.fromEntries(decisions.map((d) => [d.unit.id, d])); |
| 575 | assert.equal(by.events.deploy, false); |
| 576 | assert.equal(by.events.reason, "nothing it is built from changed"); |
| 577 | assert.equal(by.repos.deploy, true); |
| 578 | assert.match(by.repos.reason, /crates\/scan\/src\/lib.rs via crates\/scan/); |
| 579 | assert.equal(by.pages.deploy, false); |
| 580 | assert.equal(by.pages.reason, "up to date"); |
| 581 | assert.equal(by.web.deploy, true); |
| 582 | assert.match(by.web.reason, /never deployed/); |
| 583 | }); |
| 584 | |
| 585 | test("decide: --force deploys unchanged units; a commit missing from history deploys", () => { |
| 586 | const forced = decide([unit("events")], { live: { events: { sha: HEAD } }, head: HEAD, force: true, gitApi: fakeGit([]) }); |
| 587 | assert.equal(forced[0].deploy, true); |
| 588 | const shallow = decide([unit("events")], { live: { events: { sha: OLD } }, head: HEAD, gitApi: fakeGit([], { has: false }) }); |
| 589 | assert.equal(shallow[0].deploy, true); |
| 590 | assert.match(shallow[0].reason, /does not have/); |
| 591 | }); |
| 592 | |
| 593 | test("decide: Cargo.lock counts only where it reaches", () => { |
| 594 | const locks = { [`${OLD}:Cargo.lock`]: lock("0.10.8"), [`${HEAD}:Cargo.lock`]: lock("0.10.9") }; |
| 595 | const units = [unit("events"), unit("webhooks")]; |
| 596 | const live = { events: { sha: OLD }, webhooks: { sha: OLD } }; |
| 597 | const decisions = decide(units, { live, head: HEAD, gitApi: fakeGit(["Cargo.lock"], { locks }) }); |
| 598 | assert.deepEqual( |
| 599 | decisions.map((d) => [d.unit.id, d.deploy]), |
| 600 | [ |
| 601 | ["events", false], |
| 602 | ["webhooks", true], |
| 603 | ], |
| 604 | ); |
| 605 | }); |
| 606 | |
| 607 | test("decide: the runner's image rebuilds only when what it is built from changed", () => { |
| 608 | const live = { runner: { sha: OLD } }; |
| 609 | const code = decide([unit("runner")], { live, head: HEAD, gitApi: fakeGit(["services/runner/src/index.ts"]) }); |
| 610 | assert.deepEqual([code[0].deploy, code[0].image], [true, false]); |
| 611 | const image = decide([unit("runner")], { live, head: HEAD, gitApi: fakeGit(["crates/runner/src/main.rs"]) }); |
| 612 | assert.deepEqual([image[0].deploy, image[0].image], [true, true]); |
| 613 | }); |
| 614 | |
| 615 | test("the plan as data: migrations, and each stage's units in jobs that share a build", () => { |
| 616 | const units = ["events", "repos", "projects", "api", "web", "docs"].map(unit); |
| 617 | const decisions = units.map((u) => ({ unit: u, deploy: true, reason: "x", since: null, image: false })); |
| 618 | const data = planJson(stack, decisions, { events: { pending: ["0003_x.sql"] }, repos: { pending: [] } }, HEAD); |
| 619 | assert.deepEqual(data.migrations, [{ unit: "events", database: "g1t-events", pending: ["0003_x.sql"] }]); |
| 620 | assert.deepEqual(data.stages.core.jobs, [ |
| 621 | { group: "rust", units: "events,repos", rust: true, image: false }, |
| 622 | { group: "ts", units: "projects", rust: false, image: false }, |
| 623 | ]); |
| 624 | assert.deepEqual(data.stages.edge.jobs, [{ group: "rust", units: "api", rust: true, image: false }]); |
| 625 | assert.deepEqual(data.stages.front.jobs, [ |
| 626 | { group: "web", units: "web", rust: false, image: false }, |
| 627 | { group: "docs", units: "docs", rust: false, image: false }, |
| 628 | ]); |
| 629 | assert.deepEqual(data.stage_order, ["core", "edge", "front"]); |
| 630 | assert.deepEqual(buildGroups([]), []); |
| 631 | // Eleven Rust workers go to three jobs; a unit whose image rebuilds gets its own. |
| 632 | const core = stack.units.filter((u) => u.stage === "core"); |
| 633 | const jobs = buildGroups(core, ["runner"]); |
| 634 | assert.deepEqual( |
| 635 | jobs.filter((j) => j.rust).map((j) => j.units.split(",").length), |
| 636 | [4, 4, 3], |
| 637 | ); |
| 638 | assert.ok(jobs.some((j) => j.group === "runner-image" && j.units === "runner" && j.image && !j.rust)); |
| 639 | assert.ok(!jobs.find((j) => j.group === "ts").units.includes("runner")); |
| 640 | }); |
| 641 | |
| 642 | test("units are picked by short name, folder or Worker name", () => { |
| 643 | assert.deepEqual( |
| 644 | pick(stack, ["billing,services/web".replace("services/web", "apps/web"), "g1t-api"]).map((u) => u.id), |
| 645 | ["billing", "web", "api"], |
| 646 | ); |
| 647 | assert.throws(() => pick(stack, ["nope"]), /No unit called nope/); |
| 648 | }); |
| 649 | |
| 650 | test("a CI job installs only what its units need", () => { |
| 651 | const npm = npmWorkspace(); |
| 652 | assert.deepEqual(npmCiArgs([unit("events"), unit("repos")], npm), ["ci", "--prefer-offline", "--no-audit", "--no-fund", "--workspaces=false"]); |
| 653 | assert.deepEqual(npmCiArgs([unit("events"), unit("status")], npm), [ |
| 654 | "ci", |
| 655 | "--prefer-offline", |
| 656 | "--no-audit", |
| 657 | "--no-fund", |
| 658 | "--include-workspace-root", |
| 659 | "-w", |
| 660 | "@g1t/contracts", |
| 661 | "-w", |
| 662 | "@g1t/status", |
| 663 | "-w", |
| 664 | "@g1t/theme", |
| 665 | ]); |
| 666 | }); |
| 667 | |
| 668 | // ── Cloudflare's answers ────────────────────────────────────────────────── |
| 669 | |
| 670 | const version = (id, number, message, triggered = "deployment") => ({ |
| 671 | id, |
| 672 | number, |
| 673 | metadata: { created_on: "2026-10-05T00:00:00Z", author_email: "a@b" }, |
| 674 | annotations: { "workers/triggered_by": triggered, ...(message ? { "workers/message": message } : {}) }, |
| 675 | }); |
| 676 | |
| 677 | test("a deploy is annotated with its commit, and read back", () => { |
| 678 | const { message, tag } = annotation(HEAD, "A subject ".repeat(20)); |
| 679 | assert.ok(message.length <= 100); |
| 680 | assert.equal(commitFrom(message), HEAD); |
| 681 | assert.equal(tag, `g1t-${HEAD.slice(0, 12)}`); |
| 682 | assert.equal(commitFrom(message.replace("g1t-deploy", "g1t-deploy-dirty")), null); |
| 683 | assert.equal(commitFrom("deployed by hand"), null); |
| 684 | }); |
| 685 | |
| 686 | test("the live commit: the live version's, looking through secret changes", () => { |
| 687 | const versions = [version("v1", 1, annotation(OLD).message), version("v2", 2, null, "secret"), version("v3", 3, null, "version_upload")]; |
| 688 | const status = (id) => ({ versions: [{ version_id: id, percentage: 100 }] }); |
| 689 | assert.equal(liveCommit(status("v1"), versions).sha, OLD); |
| 690 | assert.equal(liveCommit(status("v2"), versions).sha, OLD); |
| 691 | assert.equal(liveCommit(status("v3"), versions).sha, null); |
| 692 | assert.match(liveCommit(status("v9"), versions).why, /not among/); |
| 693 | const split = liveCommit( |
| 694 | { |
| 695 | versions: [ |
| 696 | { version_id: "v1", percentage: 10 }, |
| 697 | { version_id: "v2", percentage: 90 }, |
| 698 | ], |
| 699 | }, |
| 700 | versions, |
| 701 | ); |
| 702 | assert.equal(split.sha, OLD); |
| 703 | assert.equal(split.split, true); |
| 704 | }); |
| 705 | |
| 706 | test("Wrangler's output: pending migrations and the version a deploy made", () => { |
| 707 | const pending = ` |
| 708 | ⛅️ wrangler 4.146.0 |
| 709 | Resource location: remote |
| 710 | Migrations to be applied: |
| 711 | ┌──────────────────────┐ |
| 712 | │ Name │ |
| 713 | ├──────────────────────┤ |
| 714 | │ 0021_confidence.sql │ |
| 715 | ├──────────────────────┤ |
| 716 | │ 0022_more.sql │ |
| 717 | └──────────────────────┘`; |
| 718 | assert.deepEqual(pendingFrom(pending), ["0021_confidence.sql", "0022_more.sql"]); |
| 719 | assert.deepEqual(pendingFrom("Resource location: remote\n\n✅ No migrations to apply!"), []); |
| 720 | assert.equal(versionFrom("Deployed g1t-events triggers\nCurrent Version ID: 2c7fc93a-82d9-4850-8a77-ba887d157a4f\n"), "2c7fc93a-82d9-4850-8a77-ba887d157a4f"); |
| 721 | }); |
| 722 | |
| 723 | // Cloudflare's REST answers, as the API sends them (Wrangler's --json |
| 724 | // prints the first deployment, and the versions' items). |
| 725 | const AUTH = { token: "t", account: "acct" }; |
| 726 | const ok = (result) => ({ success: true, errors: [], messages: [], result }); |
| 727 | const refused = (code, message) => ({ success: false, errors: [{ code, message }], messages: [], result: null }); |
| 728 | /** A fetch that answers by path: { "GET /path": [status, body] }. */ |
| 729 | function fakeFetch(answers, calls = []) { |
| 730 | return async (url, init) => { |
| 731 | const path = url.replace("https://api.cloudflare.com/client/v4", ""); |
| 732 | calls.push({ path, init }); |
| 733 | const found = answers[`${init.method} ${path}`]; |
| 734 | if (!found) throw new Error(`unexpected ${init.method} ${path}`); |
| 735 | const [status, body] = found; |
| 736 | return { status, text: async () => (typeof body === "string" ? body : JSON.stringify(body)) }; |
| 737 | }; |
| 738 | } |
| 739 | const SCRIPT = "/accounts/acct/workers/scripts/g1t-events"; |
| 740 | const deploymentsAnswer = (id) => |
| 741 | ok({ |
| 742 | deployments: [ |
| 743 | { |
| 744 | id: "d2", |
| 745 | source: "wrangler", |
| 746 | strategy: "percentage", |
| 747 | versions: [{ version_id: id, percentage: 100 }], |
| 748 | annotations: { "workers/triggered_by": "deployment" }, |
| 749 | }, |
| 750 | { id: "d1", source: "wrangler", strategy: "percentage", versions: [{ version_id: "v1", percentage: 100 }] }, |
| 751 | ], |
| 752 | }); |
| 753 | const versionsAnswer = ok({ items: [version("v1", 1, annotation(OLD).message), version("v2", 2, null, "secret")] }); |
| 754 | |
| 755 | test("the API's answers: the live commit as Wrangler's would give it", async () => { |
| 756 | const calls = []; |
| 757 | const fetchImpl = fakeFetch( |
| 758 | { [`GET ${SCRIPT}/deployments`]: [200, deploymentsAnswer("v2")], [`GET ${SCRIPT}/versions?deployable=true`]: [200, versionsAnswer] }, |
| 759 | calls, |
| 760 | ); |
| 761 | const found = await readLive(unit("events"), { auth: AUTH, fetchImpl }); |
| 762 | assert.equal(found.sha, OLD); |
| 763 | assert.equal(found.version, "v2"); |
| 764 | assert.equal(found.at, "2026-10-05T00:00:00Z"); |
| 765 | assert.equal(calls[0].init.headers.authorization, "Bearer t"); |
| 766 | // The same as liveCommit over what Wrangler printed. |
| 767 | assert.deepEqual( |
| 768 | liveFromApi("w", deploymentsAnswer("v2").result, versionsAnswer.result), |
| 769 | liveCommit(deploymentsAnswer("v2").result.deployments[0], versionsAnswer.result.items), |
| 770 | ); |
| 771 | // Versions that cannot be read: the live one is not among them. |
| 772 | assert.match(liveFromApi("w", deploymentsAnswer("v2").result, null).why, /not among/); |
| 773 | // No deployment at all is an error, as `deployments status` made it. |
| 774 | assert.match(liveFromApi("w", { deployments: [] }, versionsAnswer.result).error, /no deployments/); |
| 775 | }); |
| 776 | |
| 777 | test("the API's answers: a Worker never deployed, and a refusal, never throw", async () => { |
| 778 | const missing = fakeFetch({ |
| 779 | [`GET ${SCRIPT}/deployments`]: [404, refused(10007, "workers.api.error.script_not_found")], |
| 780 | [`GET ${SCRIPT}/versions?deployable=true`]: [404, refused(10007, "workers.api.error.script_not_found")], |
| 781 | }); |
| 782 | assert.deepEqual(await readLive(unit("events"), { auth: AUTH, fetchImpl: missing }), { sha: null, missing: true, why: "never deployed" }); |
| 783 | const denied = fakeFetch({ |
| 784 | [`GET ${SCRIPT}/deployments`]: [400, refused(10000, "Authentication error")], |
| 785 | [`GET ${SCRIPT}/versions?deployable=true`]: [400, refused(10000, "Authentication error")], |
| 786 | }); |
| 787 | const found = await readLive(unit("events"), { auth: AUTH, fetchImpl: denied }); |
| 788 | assert.equal(found.sha, null); |
| 789 | assert.match(found.error, /Authentication error \(10000\)/); |
| 790 | const broken = async () => { |
| 791 | throw new Error("connect ECONNREFUSED"); |
| 792 | }; |
| 793 | const offline = await readLive(unit("events"), { auth: AUTH, fetchImpl: broken }); |
| 794 | assert.match(offline.error, /ECONNREFUSED/); |
| 795 | const garbled = fakeFetch({ [`GET ${SCRIPT}/deployments`]: [200, "<html>"], [`GET ${SCRIPT}/versions?deployable=true`]: [200, versionsAnswer] }); |
| 796 | assert.match((await readLive(unit("events"), { auth: AUTH, fetchImpl: garbled })).error, /<html>/); |
| 797 | }); |
| 798 | |
| 799 | test("the API is used only with the token Wrangler would be given", () => { |
| 800 | assert.equal(apiAuth({ CLOUDFLARE_API_TOKEN: "shell" }), null); |
| 801 | assert.deepEqual(apiAuth({ CI: "true", CLOUDFLARE_API_TOKEN: "ci", CLOUDFLARE_ACCOUNT_ID: "a" }), { token: "ci", account: "a" }); |
| 802 | assert.equal(apiAuth({ CLOUDFLARE_DEPLOY_TOKEN: "mine" }).token, "mine"); |
| 803 | assert.equal(apiAuth({ CLOUDFLARE_DEPLOY_TOKEN: "mine" }).account, "1e6f2cffa3f445920836e8ebe446bb58"); |
| 804 | }); |
| 805 | |
| 806 | test("pending migrations: the folder's files less the names in d1_migrations", async () => { |
| 807 | const events = unit("events"); |
| 808 | const db = databaseOf(events); |
| 809 | assert.equal(db.id, events.config.d1_databases[0].database_id); |
| 810 | assert.equal(db.table, "d1_migrations"); |
| 811 | const files = migrationFiles(join(ROOT, db.dir)); |
| 812 | assert.ok(files.length > 2 && files.every((f) => f.endsWith(".sql"))); |
| 813 | assert.deepEqual(files, [...files].sort()); |
| 814 | |
| 815 | assert.deepEqual( |
| 816 | pendingAgainst(["0001_a.sql", "0002_b.sql", "0003_c.sql"], [{ results: [{ name: "0001_a.sql" }, { name: "0002_b.sql" }], success: true, meta: {} }]), |
| 817 | ["0003_c.sql"], |
| 818 | ); |
| 819 | assert.deepEqual(pendingAgainst(["0001_a.sql"], [{ results: [], success: true }]), ["0001_a.sql"]); |
| 820 | |
| 821 | const query = `POST /accounts/acct/d1/database/${db.id}/query`; |
| 822 | const calls = []; |
| 823 | const applied = files.slice(0, -1).map((name, i) => ({ name, id: i + 1 })); |
| 824 | const found = await pendingMigrations(events, { |
| 825 | auth: AUTH, |
| 826 | fetchImpl: fakeFetch({ [query]: [200, ok([{ results: applied, success: true, meta: {} }])] }, calls), |
| 827 | }); |
| 828 | assert.deepEqual(found, { pending: files.slice(-1) }); |
| 829 | assert.match(JSON.parse(calls[0].init.body).sql, /^SELECT name FROM "d1_migrations"/); |
| 830 | const upToDate = await pendingMigrations(events, { |
| 831 | auth: AUTH, |
| 832 | fetchImpl: fakeFetch({ [query]: [200, ok([{ results: files.map((name) => ({ name })) }])] }), |
| 833 | }); |
| 834 | assert.deepEqual(upToDate, { pending: [] }); |
| 835 | // A database never migrated has no table: everything is pending. |
| 836 | const fresh = await pendingMigrations(events, { |
| 837 | auth: AUTH, |
| 838 | fetchImpl: fakeFetch({ [query]: [400, refused(7500, "no such table: d1_migrations: SQLITE_ERROR")] }), |
| 839 | }); |
| 840 | assert.deepEqual(fresh, { pending: files }); |
| 841 | const denied = await pendingMigrations(events, { auth: AUTH, fetchImpl: fakeFetch({ [query]: [400, refused(10000, "Authentication error")] }) }); |
| 842 | assert.match(denied.error, /Authentication error/); |
| 843 | }); |
| 844 | |
| 845 | test("the pool runs everything, no more than its limit at once", async () => { |
| 846 | let running = 0; |
| 847 | let most = 0; |
| 848 | const out = await pool([1, 2, 3, 4, 5, 6, 7], 3, async (n) => { |
| 849 | running++; |
| 850 | most = Math.max(most, running); |
| 851 | await new Promise((resolve) => setTimeout(resolve, 5)); |
| 852 | running--; |
| 853 | return n * 2; |
| 854 | }); |
| 855 | assert.deepEqual(out, [2, 4, 6, 8, 10, 12, 14]); |
| 856 | assert.equal(most, 3); |
| 857 | }); |
| 858 | |
| 859 | // ── Everything else that reads the list ─────────────────────────────────── |
| 860 | |
| 861 | test("self-hosting builds every Rust service the manifest says it runs", () => { |
| 862 | const dockerfile = readFileSync(join(ROOT, "deploy/self-host/Dockerfile"), "utf8"); |
| 863 | const loops = [...dockerfile.matchAll(/for service in ([a-z ]+); do/g)].map((m) => m[1].trim().split(/\s+/).sort()); |
| 864 | const wanted = stack.units |
| 865 | .filter((u) => u.self_host === "run" && u.kind === "rust-worker") |
| 866 | .map((u) => u.path.split("/").pop()) |
| 867 | .sort(); |
| 868 | assert.ok(loops.length >= 2); |
| 869 | for (const loop of loops) assert.deepEqual(loop, wanted); |
| 870 | }); |
| 871 | |
| 872 | test("the self-hosting architecture page names every unit", () => { |
| 873 | const page = "apps/docs/src/content/docs/guides/self-hosting-architecture.md"; |
| 874 | const doc = readFileSync(join(ROOT, page), "utf8"); |
| 875 | for (const u of stack.units) assert.ok(doc.includes(`| \`${u.path}\` |`), `${u.path} is missing from ${page}`); |
| 876 | }); |
| 877 | |
| 878 | test("the architecture's services page names every unit, with the services it binds to", () => { |
| 879 | const page = "apps/docs/src/content/docs/architecture/services.md"; |
| 880 | const doc = readFileSync(join(ROOT, page), "utf8"); |
| 881 | for (const u of stack.units) { |
| 882 | const row = doc.split(/\r?\n/).find((line) => line.startsWith(`| \`${u.path}\` |`)); |
| 883 | assert.ok(row, `${u.path} is missing from ${page}`); |
| 884 | // The last cell lists the services it calls, by name without "g1t-". |
| 885 | const cells = row.split("|").map((cell) => cell.trim()); |
| 886 | const listed = [...cells[cells.length - 2].matchAll(/`([a-z-]+)`/g)].map((m) => m[1]).sort(); |
| 887 | const config = parseJsonc(readFileSync(join(ROOT, u.path, "wrangler.jsonc"), "utf8")); |
| 888 | const bound = [...new Set((config.services ?? []).map((s) => s.service.replace(/^g1t-/, "")))].sort(); |
| 889 | assert.deepEqual(listed, bound, `${page}: the Calls cell for ${u.path} should list ${bound.join(", ") || "none"}`); |
| 890 | } |
| 891 | }); |
| 892 | |
| 893 | test("resolveStack works on a manifest with no workspace crates or packages", () => { |
| 894 | const bare = resolveStack(loadStack(), { cargo: new Map(), npm: new Map() }); |
| 895 | assert.deepEqual(bare.units.find((u) => u.id === "events").dependsOn, []); |
| 896 | }); |
| 897 | |
| 898 | test("decide: a commit older than what runs is never deployed by accident, even forced; --rollback means it", () => { |
| 899 | const newer = { |
| 900 | has: () => true, |
| 901 | changed: () => ["services/events/src/lib.rs"], |
| 902 | show: () => "", |
| 903 | isAncestor: (older, newer) => older === HEAD && newer === OLD, |
| 904 | }; |
| 905 | const refused = decide([unit("events")], { live: { events: { sha: OLD } }, head: HEAD, force: true, gitApi: newer }); |
| 906 | assert.equal(refused[0].deploy, false); |
| 907 | assert.match(refused[0].reason, /newer than this commit/); |
| 908 | const meant = decide([unit("events")], { live: { events: { sha: OLD } }, head: HEAD, rollback: true, gitApi: newer }); |
| 909 | assert.equal(meant[0].deploy, true); |
| 910 | assert.match(meant[0].reason, /rolling back/); |
| 911 | }); |
| 912 | |
| 913 | test("a deploy by hand reports to the repository on g1t, and a workflow's does not", async () => { |
| 914 | const { g1tRemote, inWorkflow, deployToken, reportDeployment } = await import("./report.mjs"); |
| 915 | 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" }); |
| 916 | assert.equal(g1tRemote(["git@github.com:flagon-io/g1t.git"]), null); |
| 917 | assert.equal(inWorkflow({ GITHUB_ACTIONS: "true" }), true); |
| 918 | assert.equal(inWorkflow({}), false); |
| 919 | assert.equal(deployToken({ G1T_DEPLOY_TOKEN: " g1t_x \n" }, "/nowhere"), "g1t_x"); |
| 920 | assert.equal(deployToken({}, "/nowhere"), null); |
| 921 | let called = false; |
| 922 | const settle = await reportDeployment({ |
| 923 | head: "abc", |
| 924 | subject: "s", |
| 925 | units: ["web"], |
| 926 | log: () => {}, |
| 927 | env: { GITHUB_ACTIONS: "true", G1T_DEPLOY_TOKEN: "t" }, |
| 928 | fetchImpl: () => { |
| 929 | called = true; |
| 930 | }, |
| 931 | }); |
| 932 | assert.equal(settle, null); |
| 933 | assert.equal(called, false); |
| 934 | }); |
| 935 | |
| 936 | // What a deploy said when Cloudflare's API failed under it: the reason is |
| 937 | // in the ✘ [ERROR] block, and the last lines are only the request's trace. |
| 938 | const API_FAILED = [ |
| 939 | "Uploaded g1t-runner (12.31 sec)", |
| 940 | "✘ [ERROR] A request to the Cloudflare API (/accounts/abc/workers/scripts/g1t-runner/versions) failed.", |
| 941 | "", |
| 942 | " Service unavailable [code: 10013]", |
| 943 | "", |
| 944 | " If you think this is a bug, please open an issue at: https://github.com/cloudflare/workers-sdk/issues/new/choose", |
| 945 | "", |
| 946 | ' "result": {', |
| 947 | ' "id": "g1t-runner",', |
| 948 | " GET /accounts/abc/workers/services/g1t-runner -> 200 OK", |
| 949 | " Cloudflare Ray ID: a49663530d5eebe3-SJC", |
| 950 | ].join("\n"); |
| 951 | |
| 952 | test("a failed wrangler command is reported by its error, not its trace", () => { |
| 953 | const said = wranglerError(API_FAILED); |
| 954 | assert.match(said, /^✘ \[ERROR\] A request to the Cloudflare API/); |
| 955 | assert.match(said, /Service unavailable \[code: 10013\]/); |
| 956 | // No error block: its last lines, as before. |
| 957 | assert.equal(wranglerError("one\ntwo\nthree", 2), "two\nthree"); |
| 958 | }); |
| 959 | |
| 960 | test("Cloudflare failing is tried again; a mistake in what is deployed is not", () => { |
| 961 | assert.equal(retryableDeploy(API_FAILED), true); |
| 962 | assert.equal(retryableDeploy('✘ [ERROR] Build failed with 1 error:\n src/index.ts:3:7: ERROR: Could not resolve "./nope"'), false); |
| 963 | assert.equal(retryableDeploy('✘ [ERROR] Processing wrangler.jsonc configuration:\n - "main" is not a valid path'), false); |
| 964 | assert.equal(retryableDeploy("fetch failed: ECONNRESET"), true); |
| 965 | }); |
| 966 | |
| 967 | test("sandboxes roll over at once when their image or container settings changed, and not otherwise", () => { |
| 968 | const unit = { id: "runner", path: "services/runner" }; |
| 969 | assert.equal(containersRollout(unit, { image: true, files: [] }), "immediate"); |
| 970 | assert.equal(containersRollout(unit, { image: false, files: ["services/runner/wrangler.jsonc"] }), "immediate"); |
| 971 | assert.equal(containersRollout(unit, { image: false, files: ["services/runner/src/egress.ts"] }), "none"); |
| 972 | assert.equal(containersRollout(unit, { image: false, files: ["services/runnerx/wrangler.jsonc"] }), "none"); |
| 973 | assert.equal(containersRollout(unit, { image: false, files: [] }, { rebuildImage: true }), "immediate"); |
| 974 | }); |
| 975 | |
| 976 | test("the deploy tool itself parses: a test that never imports it would not notice", () => { |
| 977 | execFileSync(process.execPath, ["--check", join(import.meta.dirname, "..", "deploy.mjs")]); |
| 978 | }); |