iterate.com / cloud

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

cloud / internal-packages / installer / test / deployments.mjsmain at aacbc74

// deployments.mjs — "Your deployments" (worker/deployments.js `deploymentsOf`) against an account
// in memory with more zones than the page reads routes of: which zones' routes are read, which
// deployments are found, and when the page says that it did not look at every domain.
// Run: node test/deployments.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import { deploymentsOf, taggedCommits, zonesOf } from "../worker/deployments.js";
import { commitsOf } from "../worker/stack-commits.js";
import { CLOUDFLARE_TOKEN_EDITION } from "../worker/scopes.js";

const ACCOUNT = { id: "a".repeat(32), name: "Ada's account" };
const nameOf = (zone) => zone.replace(/[^a-z0-9]+/g, "-");
const idOf = (zone) => `id-${zone}`;

/** An account with `zones` and Workers; `routes` says which Worker a zone's every name leads to.
 *  `tags`: a Worker's tags at Cloudflare, by its name. `run`: what this Cloud's deploy run for a
 *  stack answers. `commits`: the commits of iterate this Cloud has. `owner`: who this Cloud
 *  deployed the stacks for; none for stacks that somebody deployed another way. */
function account({ zones, workers, routes, tags = {}, run = null, commits, owner }) {
  const read = [];
  const cf = async (method, path) => {
    assert.equal(method, "GET");
    const ok = (result) => ({ success: true, result });
    if (path === `/accounts/${ACCOUNT.id}/workers/scripts`)
      return ok(workers.map((id) => ({ id, tags: tags[id] || [] })));
    if (path === `/accounts/${ACCOUNT.id}/workers/domains`) return ok([]);
    const page = /^\/zones\?account\.id=[a-z]+&per_page=50&order=name&page=(\d+)$/.exec(path);
    if (page)
      return ok(
        zones
          .slice((page[1] - 1) * 50, page[1] * 50)
          .map((name) => ({ id: idOf(name), name, status: "active" })),
      );
    const zone = /^\/zones\/id-(.+)\/workers\/routes$/.exec(path)?.[1];
    if (zone) {
      read.push(zone);
      return ok(routes[zone] ? [{ pattern: `*.${zone}/*`, script: routes[zone] }] : []);
    }
    throw new Error(`no such call here: ${path}`);
  };
  const env = {
    DEPLOYER: { getByName: () => ({ status: async () => run }) },
    // the record of a first deploy from this Cloud says who signs in to the stack
    SESSIONS: {
      get: async (key) => (owner && key.startsWith("dep:") ? JSON.stringify({ owner }) : null),
    },
  };
  return {
    read,
    list: (timing) =>
      deploymentsOf({
        cf,
        nameOf,
        accounts: [ACCOUNT],
        env,
        standIn: async () => true,
        timing,
        commits,
      }),
  };
}
/** 120 zones that are nobody's stack. */
const many = Array.from({ length: 120 }, (_, i) => `zone${String(i).padStart(3, "0")}.com`);
const stack = (name) => ["boundary", "auth", "mind"].map((part) => `iterate-${name}-${part}`);

/** Cloudflare's zone list for `count` zones: an answer takes a turn of the event loop, and
 *  `together` is the most answers that were awaited at one time. `says`: each answer says how
 *  many pages there are, as Cloudflare's does. */
function zoneList(count, says) {
  const seen = { asked: [], together: 0 };
  let open = 0;
  const cf = async (_method, path) => {
    const page = Number(/&page=(\d+)$/.exec(path)[1]);
    seen.asked.push(page);
    seen.together = Math.max(seen.together, ++open);
    await new Promise((done) => setTimeout(done, 5));
    open--;
    const result = Array.from({ length: count }, (_, i) => ({ name: `zone${i}.com` })).slice(
      (page - 1) * 50,
      page * 50,
    );
    return {
      success: true,
      result,
      ...(says && { result_info: { total_pages: Math.ceil(count / 50) } }),
    };
  };
  return { cf, seen };
}

test("an account's zones: after the first answer says how many pages there are, the others are asked together", async () => {
  const { cf, seen } = zoneList(440, true);
  const { zones, errors } = await zonesOf(cf, "a");
  assert.equal(zones.length, 440);
  assert.equal(new Set(zones.map((zone) => zone.name)).size, 440);
  assert.equal(zones[0].name, "zone0.com");
  assert.deepEqual(errors, []);
  assert.deepEqual(seen.asked, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
  assert.equal(seen.together, 8);
});

test("an account's zones: answers that do not say how many pages there are are followed one by one, and one page is one call", async () => {
  const many = zoneList(120, false);
  assert.equal((await zonesOf(many.cf, "a")).zones.length, 120);
  assert.deepEqual(many.seen.asked, [1, 2, 3]);
  assert.equal(many.seen.together, 1);
  const few = zoneList(7, true);
  assert.equal((await zonesOf(few.cf, "a")).zones.length, 7);
  assert.deepEqual(few.seen.asked, [1]);
  // exactly 50 zones and no page count: the next page is asked, and it is empty
  const fifty = zoneList(50, false);
  assert.equal((await zonesOf(fifty.cf, "a")).zones.length, 50);
  assert.deepEqual(fifty.seen.asked, [1, 2]);
});

test("the timing of a read holds counts and milliseconds alone, no name and no id", async () => {
  const { read, list } = account({
    zones: many,
    workers: stack("homelab"),
    routes: { "zone007.com": "iterate-homelab-boundary" },
  });
  const timing = { accounts: [] };
  await list(timing);
  assert.equal(read.length, 40);
  assert.deepEqual(Object.keys(timing).sort(), ["accounts", "deployments", "listedMs", "totalMs"]);
  assert.deepEqual(
    timing.accounts.map((took) => [took.workers, took.stacks, took.zones, took.routes]),
    [[3, 1, 120, 40]],
  );
  for (const value of Object.values(timing.accounts[0])) assert.equal(typeof value, "number");
});

test("a stack with its zone's name: the routes of that zone alone are read, and nothing is said", async () => {
  const { read, list } = account({
    zones: [...many, "zzz-example.com"],
    workers: stack("zzz-example-com"),
    routes: { "zzz-example.com": "iterate-zzz-example-com-boundary" },
  });
  const { deployments, notes } = await list();
  assert.deepEqual(read, ["zzz-example.com"]);
  assert.deepEqual(notes, []);
  assert.deepEqual(
    deployments.map((d) => [d.domain, d.name, d.incomplete, d.updatable]),
    [["zzz-example.com", "zzz-example-com", false, true]],
  );
});

test("an account with no stack: no zone's routes are read", async () => {
  const { read, list } = account({ zones: many, workers: ["shop"], routes: {} });
  assert.deepEqual(await list(), { deployments: [], notes: [] });
  assert.deepEqual(read, []);
});

test("a stack with a name of its own, on one of the first zones: more zones are read until 40, it is found, nothing is said", async () => {
  const { read, list } = account({
    zones: many,
    workers: stack("homelab"),
    routes: { "zone007.com": "iterate-homelab-boundary" },
  });
  const { deployments, notes } = await list();
  assert.equal(read.length, 40);
  assert.deepEqual(notes, []);
  assert.deepEqual(
    deployments.map((d) => [d.domain, d.name]),
    [["zone007.com", "homelab"]],
  );
});

test("a stack with a name of its own, on a zone that was not read: the page says which deployment it did not find", async () => {
  const { read, list } = account({
    zones: many,
    workers: [...stack("homelab"), ...stack("zone003-com")],
    routes: {
      "zone003.com": "iterate-zone003-com-boundary",
      "zone099.com": "iterate-homelab-boundary",
    },
  });
  const { deployments, notes } = await list();
  assert.equal(read.length, 40);
  assert.equal(read[0], "zone003.com");
  assert.deepEqual(notes, [
    "Ada's account has 120 domains, and iterate looked at 40 of them. It did not find the domain of the deployment homelab.",
  ]);
  assert.deepEqual(
    deployments.map((d) => d.domain),
    ["zone003.com"],
  );
});

test("parts of a stack and no Worker that serves the domain: found by the zone's name, as incomplete", async () => {
  const { read, list } = account({
    zones: [...many, "zzz-example.com"],
    workers: ["iterate-zzz-example-com-mind"],
    routes: {},
  });
  const { deployments, notes } = await list();
  assert.deepEqual(read, ["zzz-example.com"]);
  assert.deepEqual(notes, []);
  assert.deepEqual(
    deployments.map((d) => [d.domain, d.incomplete, d.updatable]),
    [["zzz-example.com", true, false]],
  );
});

// WHICH ITERATE A STACK RUNS, AND WHETHER THIS CLOUD HAS IT (the card's side of the guard; the run's
// own check is in test/update-guard.mjs)
const hex = (letter) => letter.repeat(40);
const CLOUD = hex("c");
const BEHIND = hex("b");
const AHEAD = hex("f");
const has = { own: CLOUD, all: new Set([CLOUD, BEHIND]) };
/** One stack on ada.com: what its boundary Worker's tags and this Cloud's run say. */
const one = async ({ tags = [], run, commits = has, owner }) => {
  const { list } = account({
    zones: ["ada.com"],
    workers: stack("ada-com"),
    routes: { "ada.com": "iterate-ada-com-boundary" },
    tags: { "iterate-ada-com-boundary": tags, "iterate-ada-com-mind": [`iterate-commit:${AHEAD}`] },
    run,
    commits,
    owner,
  });
  const { deployments } = await list();
  assert.equal(deployments.length, 1);
  return deployments[0];
};
const succeeded = (commit) => ({ status: "succeeded", endedAt: 1, result: { commit } });

test("a stack whose Worker names a commit this Cloud has: the card says which, and nothing more", async () => {
  const d = await one({ tags: ["alchemy:id:x", `iterate-commit:${BEHIND}`] });
  assert.equal(d.commit, BEHIND);
  assert.equal(d.foreign, null);
  assert.equal(d.updatable, true);
});

test("a stack whose Worker names a commit this Cloud does not have: the card says both commits, and the update stays possible for one who asks for it", async () => {
  const d = await one({ tags: [`iterate-commit:${AHEAD}`], run: succeeded(BEHIND) });
  assert.equal(d.commit, AHEAD);
  // the Worker's tag wins over this Cloud's record: somebody deployed it another way since
  assert.equal(d.run.commit, BEHIND);
  assert.deepEqual(d.foreign, { runs: AHEAD, cloud: CLOUD });
  assert.equal(d.updatable, true);
  assert.equal(d.replaceable, true);
});

test("“Update anyway” stays after a run from here that failed, for a stack this Cloud deployed too: the run that the check stopped is such a run", async () => {
  const ahead = [`iterate-commit:${AHEAD}`];
  const failed = { status: "failed", endedAt: 2, recorded: BEHIND };
  const d = await one({ tags: ahead, run: failed, owner: "ada@example.com" });
  assert.deepEqual(d.foreign, { runs: AHEAD, cloud: CLOUD });
  // no plain update after a failed run of a stack with an owner, as before
  assert.equal(d.updatable, false);
  assert.equal(d.replaceable, true);
  // what stops every update from here stops this one too
  const outside = await one({ tags: ahead, run: { ...failed, keyOutside: true }, owner: "a@b.c" });
  assert.equal(outside.replaceable, false);
  // and a stack that runs what this Cloud has needs no such press
  const known = await one({ tags: [`iterate-commit:${BEHIND}`], run: failed, owner: "a@b.c" });
  assert.equal(known.replaceable, false);
});

test("the card's Cloudflare connection is what the last deploy from here said, also after a run that failed later", async () => {
  const on = await one({ run: { ...succeeded(BEHIND), connection: true } });
  assert.equal(on.run.cloudflareToken, true);
  const failed = await one({
    run: { status: "failed", endedAt: 2, recorded: BEHIND, connection: true },
  });
  assert.equal(failed.run.cloudflareToken, true);
  const off = await one({ run: { ...succeeded(BEHIND), connection: false } });
  assert.equal(off.run.cloudflareToken, false);
});

test("the card says whether the mind's Cloudflare token is of this release's edition", async () => {
  const older = await one({ run: { ...succeeded(BEHIND), connection: true } });
  assert.equal(older.run.cloudflareTokenCurrent, false);
  const current = await one({
    run: { ...succeeded(BEHIND), connection: true, connectionEdition: CLOUDFLARE_TOKEN_EDITION },
  });
  assert.equal(current.run.cloudflareTokenCurrent, true);
});

test("a stack with no tag: this Cloud's record of its last deploy there stands in", async () => {
  const known = await one({ run: succeeded(BEHIND) });
  assert.equal(known.commit, BEHIND);
  assert.equal(known.foreign, null);
  // a Cloud that was rolled back does not have what it deployed before
  const rolledBack = await one({ run: succeeded(AHEAD) });
  assert.deepEqual(rolledBack.foreign, { runs: AHEAD, cloud: CLOUD });
});

test("a stack with no tag whose last run failed: the commit of the run before it still counts, and the card names no commit as deployed", async () => {
  const d = await one({ run: { status: "failed", endedAt: 2, recorded: AHEAD } });
  assert.equal(d.commit, null);
  assert.deepEqual(d.foreign, { runs: AHEAD, cloud: CLOUD });
});

test("a stack with no tag and no record: nothing is known, and nothing is held", async () => {
  const d = await one({});
  assert.equal(d.commit, null);
  assert.equal(d.foreign, null);
  assert.equal(d.updatable, true);
});

test("a Cloud with no list of its commits says nothing on the card: the run still checks", async () => {
  // what worker/stack-commits.js answers in a Worker that was built with no packed stack
  const d = await one({ tags: [`iterate-commit:${AHEAD}`], commits: commitsOf("") });
  assert.equal(d.commit, AHEAD);
  assert.equal(d.foreign, null);
});

test("the commit is read from the boundary Worker's one tag of that shape, and from nothing else", () => {
  const tagged = taggedCommits([
    { id: "iterate-a-boundary", tags: ["alchemy:id:x", `iterate-commit:${CLOUD}`] },
    // two commits, a branch's name, upper case, no tags at all, another part of a stack, and
    // another person's Worker: none of these names a commit
    { id: "iterate-b-boundary", tags: [`iterate-commit:${CLOUD}`, `iterate-commit:${AHEAD}`] },
    { id: "iterate-c-boundary", tags: ["iterate-commit:main"] },
    { id: "iterate-d-boundary", tags: [`iterate-commit:${"F".repeat(40)}`] },
    { id: "iterate-e-boundary" },
    { id: "iterate-f-mind", tags: [`iterate-commit:${CLOUD}`] },
    { id: "shop", tags: [`iterate-commit:${CLOUD}`] },
  ]);
  assert.deepEqual([...tagged], [["a", CLOUD]]);
  assert.deepEqual([...taggedCommits(undefined)], []);
});