iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / test / update-guard.mjsmain at aacbc74

// update-guard.mjs — AN UPDATE FROM THE CLOUD NEVER PUTS AN OLDER ITERATE OVER A NEWER ONE WITHOUT
// BEING ASKED: the run's own check (container/run.sh `not_unknown_stack`), run in bash against a
// stand-in for Cloudflare's answer, and the Worker's list of the commits it has
// (worker/stack-commits.js).
// Run: node test/update-guard.mjs
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { commitsOf, stackCommits, useCommits } from "../worker/stack-commits.js";

const hex = (letter) => letter.repeat(40);
const CLOUD = hex("c");
const BEHIND = hex("b"); // a commit the Cloud has behind its own
const AHEAD = hex("f"); // one it does not have
const tag = (commit) => `iterate-commit:${commit}`;

/** `not_unknown_stack` of run.sh, with Cloudflare's answer to the read of the Worker's settings
 *  and the image's files in a folder of their own. `{ code, out }`. */
function check({ status = 200, tags, body, list = [CLOUD, BEHIND], record = "", anyway = "" }) {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  const fn = new RegExp("^not_unknown_stack\\(\\) \\{\\n[\\s\\S]*?^\\}", "m").exec(run)[0];
  const stack = mkdtempSync(join(tmpdir(), "run-guard-"));
  writeFileSync(join(stack, "COMMIT"), `${CLOUD}\n`);
  if (list) writeFileSync(join(stack, "COMMITS"), list.map((line) => `${line}\n`).join(""));
  const said = body ?? JSON.stringify({ success: true, result: { tags } });
  writeFileSync(join(stack, "answer"), `${said}\n${status}`);
  const script = `
ITERATE_ZONE=a.com
ITERATE_NAME=a
CLOUDFLARE_ACCOUNT_ID=${"a".repeat(32)}
COMMIT_TAG="iterate-commit:"
cf_get() {
  [ "$1" = "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/iterate-a-boundary/script-settings" ] || { echo "another read: $1" >&2; exit 9; }
  cat /stack/answer
}
${fn}
not_unknown_stack
`.replaceAll("/stack/", `${stack}/`);
  const ran = spawnSync("bash", ["--norc", "-c", script], {
    encoding: "utf8",
    stdio: ["ignore", "pipe", "pipe"],
    env: {
      PATH: process.env.PATH,
      ...(record && { ITERATE_RECORD_COMMIT: record }),
      ...(anyway && { ITERATE_UPDATE_ANYWAY: anyway }),
    },
  });
  assert.equal(ran.stderr, "");
  return { code: ran.status, out: ran.stdout };
}

test("the tag's prefix in run.sh is the one that the deploy writes", () => {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  const stack = readFileSync(
    new URL("../../../core/alchemy/src/stack.ts", import.meta.url),
    "utf8",
  );
  assert.match(run, /^COMMIT_TAG="iterate-commit:"$/m);
  assert.match(stack, /^const COMMIT_TAG = "iterate-commit:";$/m);
});

test("a stack at the Cloud's own commit, or at one behind it, is updated, and nothing is said", () => {
  assert.deepEqual(check({ tags: [tag(CLOUD)] }), { code: 0, out: "" });
  assert.deepEqual(check({ tags: ["alchemy:id:x", tag(BEHIND)] }), { code: 0, out: "" });
});

test("a domain with no boundary Worker (a first deploy) is not held", () => {
  assert.deepEqual(check({ status: 404, body: '{"success":false}' }), { code: 0, out: "" });
});

test("a stack at a commit the Cloud does not have: the run stops and says which", () => {
  const { code, out } = check({ tags: [tag(AHEAD)] });
  assert.equal(code, 1);
  assert.match(
    out,
    /^Stopped: This deployment runs iterate at fffffffff, which this Cloud does not have: it is newer than the Cloud, or from another branch\. Nothing was changed\./,
  );
  assert.doesNotMatch(out, /replaces/);
});

test("“Update anyway” for that very commit runs, and the log names the commit it replaces", () => {
  const { code, out } = check({ tags: [tag(AHEAD)], anyway: AHEAD });
  assert.equal(code, 0);
  assert.match(
    out,
    /^Note: Update anyway: this deployment ran iterate at fffffffff, .* replace it with ccccccccc\.$/m,
  );
  assert.match(out, new RegExp(`^replaces ${AHEAD}$`, "m"));
});

test("“Update anyway” for another commit than the stack runs now stops: the person agreed to that one alone", () => {
  const { code, out } = check({ tags: [tag(AHEAD)], anyway: hex("e") });
  assert.equal(code, 1);
  assert.match(out, /^Stopped: This deployment runs iterate at fffffffff/);
  // and it changes nothing for a stack that the Cloud has
  assert.deepEqual(check({ tags: [tag(BEHIND)], anyway: AHEAD }), { code: 0, out: "" });
});

test("a stack with no tag: the Cloud's own record of its last deploy there stands in", () => {
  assert.deepEqual(check({ tags: [], record: BEHIND }), { code: 0, out: "" });
  // a Cloud that was rolled back does not have what it deployed before
  const { code, out } = check({ tags: [], record: AHEAD });
  assert.equal(code, 1);
  assert.match(out, /^Stopped: This deployment runs iterate at fffffffff/);
  // the tag wins over the record: somebody deployed it another way since
  assert.equal(check({ tags: [tag(AHEAD)], record: BEHIND }).code, 1);
});

test("a stack with no tag and no record is updated as before, with a note", () => {
  const { code, out } = check({ tags: ["alchemy:id:x"] });
  assert.equal(code, 0);
  assert.match(out, /^Note: Nothing records which iterate a\.com runs/);
  assert.equal(check({ body: '{"success":true,"result":{}}' }).code, 0);
});

test("an answer that cannot be read stops the run: never an update on a guess", () => {
  for (const body of ["not json", '{"success":true,"result":null}', "{}"]) {
    const { code, out } = check({ body });
    assert.equal(code, 1, body);
    assert.match(out, /^Stopped: the run could not read which iterate a\.com runs/, body);
  }
  // two tags that each name a commit
  assert.equal(check({ tags: [tag(CLOUD), tag(AHEAD)] }).code, 1);
  // a tag that names no commit: a branch's name is never written there
  const named = check({ tags: ["iterate-commit:main"] });
  assert.equal(named.code, 1);
  assert.match(named.out, /in a way this run does not understand/);
  // Cloudflare refused the read
  const refused = check({ status: 403, body: '{"success":false}' });
  assert.equal(refused.code, 1);
  assert.match(refused.out, /^Cloudflare answered 403 to GET the Worker iterate-a-boundary\.$/m);
});

test("an image with no list of its commits updates no stack that names one", () => {
  const { code, out } = check({ tags: [tag(CLOUD)], list: null });
  assert.equal(code, 1);
  assert.match(out, /does not know which versions of iterate it can update/);
});

test("the Worker's list: its own commit is the first line, and a line that is no commit is not one", () => {
  const { own, all } = commitsOf(`${CLOUD}\n${BEHIND}\nmain\n\n`);
  assert.equal(own, CLOUD);
  assert.deepEqual([...all], [CLOUD, BEHIND]);
  assert.deepEqual(commitsOf(""), { own: null, all: new Set() });
});

test("a Worker that was not built has no list; the pretend Worker gives its own", () => {
  assert.equal(stackCommits().own, null);
  useCommits(`${CLOUD}\n${BEHIND}\n`);
  assert.equal(stackCommits().own, CLOUD);
  assert.ok(stackCommits().all.has(BEHIND));
  assert.equal(stackCommits(), stackCommits());
  useCommits(null);
  assert.equal(stackCommits().own, null);
});