iterate.com / cloud

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

cloud / internal-packages / installer / worker / pretend-run.jsmain at aacbc74

// A deploy run, acted out: the same steps and log lines as a real run (deploy-run.js, run.sh), on a
// clock, with nothing deployed. The pretend deployer (pretend-deployer.js) and the flow test's fake
// play it. The domain's name sets off the awkward cases:
//   …flaky…      the first try fails (at the step named after "flaky-", else at deploy); a retry works
//   …broken…     every try fails at deploy
//   …sluggish…   each step takes four times as long
//   …stale…      the run works, and finds no Dash and no self-test page
//   …sticky…     the first try deploys, and then its token still works after the revoke
//   …older…      the iterate there is from before 11 November 2026: only "Erase and replace" runs
//   …vault…      the iterate there keeps its vault key outside Cloudflare: only "Erase and replace" runs
//   …ahead…      a first deploy leaves an iterate there that this Cloud does not have (AHEAD), as
//                a deploy from a computer after it would (pretend-deployer.js): an update stops,
//                and "Update anyway" (`anyway`) runs
// A run of "Erase and replace" (`erase`) has the erase step. With "flaky-erase" in the name, a
// first try that erases fails there.

import { forgetLinesOf } from "./cloudflare-access.js";

/** The steps of a real run (deploy-run.js STEPS), copied: that module needs a container. */
export const STEPS = [
  { id: "check", label: "Check the access to Cloudflare" },
  { id: "deploy", label: "Deploy iterate" },
  { id: "answer", label: "Wait for iterate to answer" },
  { id: "verify", label: "Check what the deploy made" },
  { id: "forget", label: "Give up the access to Cloudflare" },
];
const ERASE_STEP = { id: "erase", label: "Erase the domain and the earlier iterate" };
const stepsFor = (erase) => (erase ? [STEPS[0], ERASE_STEP, ...STEPS.slice(1)] : STEPS);
const STEP_MS = {
  check: 2000,
  erase: 5000,
  deploy: 14_000,
  answer: 5000,
  verify: 1500,
  forget: 1500,
};
export const COMMIT = "4f2a9c1d0b7e86a5c3f1e2d4b6a8c0e2f4a6b8c0";
/** A commit that the pretend Cloud does not have: what an "ahead" stack runs. */
export const AHEAD = "9d3b7a1c5e0f2a4c6e8b0d2f4a6c8e0b1d3f5a79";
/** How the stop for a vault key outside Cloudflare starts (deploy-run.js KEY_OUTSIDE), copied. */
const KEY_OUTSIDE = "Stopped: This deployment keeps its vault key outside Cloudflare.";

/** What the run says of the pages that the person's page links to. A domain whose name has
 *  "stale" is a stack older than its Dash and its self-test page. */
function pageLines(zone) {
  const site = `https://iterate.${zone}`;
  const old = /stale/.test(zone);
  /** @type {[id: string, works: boolean, words: string][]} */
  const said = [
    ["keys", true, `the page for your passkeys answers at ${site}/keys.`],
    ["members", true, `the page where you add people answers at ${site}/members.`],
    ["self-test", !old, `the self-test page (${site}/self-test answered 404).`],
    ["mcp", true, `the address for Claude Code answers at ${site}/mcp.`],
    ["dash", !old, `the Dash (https://dash.${zone}/ answered 404).`],
  ];
  return said.flatMap(([id, works, words]) => [
    [
      0.35,
      works
        ? `Works: ${words.replace(/ \(.* answered 404\)\.$/, " answers.")}`
        : `Not there: ${words}`,
    ],
    [0.35, `page ${id} ${works ? "works" : "missing"}`],
  ]);
}

/** The log lines of one step: [share of the step's time, line]. */
function linesOf(step, { zone, name, anyway = "" }) {
  const n = `iterate-${name}`;
  switch (step) {
    case "check":
      return [
        [0.2, `stack ${COMMIT}`],
        [0.6, "The token is active and can reach the account."],
        [0.9, `${zone} is active in the account.`],
        ...(anyway
          ? [
              [
                0.95,
                `Note: Update anyway: this deployment ran iterate at ${anyway.slice(0, 9)}, which iterate Cloud does not have. You asked to replace it with ${COMMIT.slice(0, 9)}.`,
              ],
              [0.97, `replaces ${anyway}`],
            ]
          : []),
      ];
    case "erase":
      return [
        [0.1, `Erasing 9 things on ${zone} and of the earlier iterate.`],
        [0.2, `Erased: ${zone}/* → Worker ${n}-ingress`],
        [0.3, `Erased: *.${zone}/* → Worker ${n}-ingress`],
        [
          0.4,
          `Erased: Email Routing for ${zone}: mail to @${zone} stops until iterate is deployed`,
        ],
        [0.5, `Erased: AAAA ${zone} → 100::`],
        [0.6, `Erased: Worker ${n}-auth, and what it stores`],
        [0.7, `Erased: Database ${n}-auth-db: the members, passkeys and grants`],
        [0.8, `Erased: R2 bucket ${n}-files, and every file in it`],
        [0.95, `Read again: nothing is left on ${zone}.`],
      ];
    case "deploy":
      return [
        [0.04, `${n}: 14 resources to create`],
        [0.12, `+ ${n}-state  Cloudflare.D1Database  created`],
        [0.2, `+ ${n}-auth-db  Cloudflare.D1Database  created`],
        [0.28, `+ ${n}-secrets  Cloudflare.KVNamespace  created`],
        [0.36, `+ ${n}-files  Cloudflare.R2Bucket  created`],
        [0.5, `+ ${n}-sandbox  Cloudflare.Container  image pushed`],
        [0.6, `+ ${n}-auth  Cloudflare.Worker  uploaded`],
        [0.68, `+ ${n}-mind  Cloudflare.Worker  uploaded`],
        [0.76, `+ ${n}-boundary  Cloudflare.Worker  uploaded`],
        [0.84, `+ ${zone}/*  Cloudflare.Route  created`],
        [0.9, `+ *.${zone}/*  Cloudflare.Route  created`],
        [0.95, `+ ${zone}  Cloudflare.EmailRouting  enabled`],
        [0.99, `${n} deployed`],
      ];
    case "answer":
      return [
        [
          0.4,
          `https://iterate.${zone}/.well-known/oauth-authorization-server answered 404, waiting`,
        ],
        [0.95, `https://iterate.${zone} answers as the issuer.`],
      ];
    case "verify":
      return [
        [0.3, `Works: iterate answers at https://iterate.${zone}.`],
        [0.32, `Works: your mind answers at https://${zone}/.`],
        // the pages that the person's page links to, as check-result.sh says them (part 8)
        ...pageLines(zone),
        [
          0.6,
          `Works: mail to ${zone} comes to iterate (Email Routing is on, and its catch-all goes to the Worker ${n}-boundary).`,
        ],
        [
          0.9,
          `Works: the page for your first passkey answers at https://iterate.${zone}/keys/first.`,
        ],
      ];
    case "forget":
      return [[0.6, forgetLinesOf({ revoke: 200, revoked: true, probe: 401, works: false })[0]]];
    default:
      return [];
  }
}
/** How a step goes wrong: the lines a real run would print. */
function failureOf(step, { zone, name, ahead = "" }) {
  switch (step) {
    case "check":
      return /older/.test(zone)
        ? [
            `Stopped: This iterate is from before a large change. It cannot be updated in place. Erase and replace it: its members, files and config repo are not kept. Your Cloudflare account has iterate-${name}-project and iterate-${name}-ingress, which the earlier iterate made. Nothing was changed.`,
          ]
        : /vault/.test(zone)
          ? [`${KEY_OUTSIDE} Update it from a computer that holds the key. Nothing was changed.`]
          : ahead
            ? [
                `Stopped: This deployment runs iterate at ${ahead.slice(0, 9)}, which this Cloud does not have: it is newer than the Cloud, or from another branch. Nothing was changed. Update it from a computer, wait until iterate Cloud is updated, or press “Update anyway” on its card in your deployments.`,
              ]
            : [`${zone} is not active in the account yet.`];
    case "erase":
      return [
        `Stopped: ${zone} changed after you saw the list of what is erased, so nothing was erased. Look at the list again.`,
      ];
    case "answer":
      return [`https://iterate.${zone} did not answer within 5 minutes.`];
    case "verify":
      return [
        `Works: iterate answers at https://iterate.${zone}.`,
        `Missing: mail to ${zone}. Email Routing is off for the domain, so iterate receives no mail.`,
      ];
    default:
      return [
        `+ iterate-${name}-state  Cloudflare.D1Database  created`,
        `✗ iterate-${name}-sandbox  Cloudflare.Container  failed`,
        "CloudflareApiError: Unauthorized: You do not have access to Cloudflare Containers. [code: 1000]",
        "The deploy failed (1).",
      ];
  }
}

/** A whole run as [ms from the start, line], when it ends, and how. A run that fails still gives
 *  up its access: the "forget" step is always its last.
 *  `runs`: the commit of iterate that the stack there runs, when something says it (as the run's
 *  own check reads it, container/run.sh `not_unknown_stack`). `anyway`: the commit the person
 *  agreed to replace. */
export function plan({ zone, name, erase, anyway, runs }, attempt) {
  // an erase replaces whatever is there, and asks nothing about it
  const ahead = !erase && runs && runs !== COMMIT ? runs : "";
  const slow = /sluggish/.test(zone) ? 4 : 1;
  const wanted = /flaky-([a-z]+)/.exec(zone)?.[1] ?? "";
  const failAt = /broken/.test(zone)
    ? "deploy"
    : (/older|vault/.test(zone) && !erase) || (ahead && anyway !== ahead)
      ? "check"
      : /flaky/.test(zone) && attempt === 1
        ? ["check", "deploy", "answer", "verify"].includes(wanted) || (wanted === "erase" && erase)
          ? wanted
          : "deploy"
        : null;
  const steps = stepsFor(!!erase);
  const timeline = [];
  let t = 400;
  const play = (step, lines, ms) => {
    timeline.push([t, `== step ${step}`]);
    for (const [share, line] of lines) timeline.push([t + Math.round(ms * share), line]);
    t += ms;
  };
  for (const { id } of steps.slice(0, -1)) {
    const ms = STEP_MS[id] * slow;
    if (id !== failAt) {
      play(id, linesOf(id, { zone, name, anyway: ahead }), ms);
      continue;
    }
    const lines = failureOf(id, { zone, name, ahead });
    play(
      id,
      lines.map((line, i) => [(i + 1) / lines.length, line]),
      Math.round(ms * 0.6),
    );
    break;
  }
  const sticky = /sticky/.test(zone) && attempt === 1 && !failAt;
  const stuck = forgetLinesOf(
    { revoke: 200, revoked: true, probe: 200, works: true },
    "This access ends by itself within the hour.",
  );
  play(
    "forget",
    sticky ? stuck.map((line, i) => [(i + 1) / 3, line]) : linesOf("forget", { zone, name }),
    STEP_MS.forget,
  );
  return {
    timeline,
    end: t + 200,
    status: failAt || sticky ? "failed" : "succeeded",
    // what the run made is there, whatever became of its access
    deployed: !failAt,
    ...(sticky && { failedAt: "forget" }),
    ...(failAt === "check" && /vault/.test(zone) && { keyOutside: true }),
    ...(!failAt && ahead && { replaced: ahead }),
    ...(erase && { erase: true, erased: failAt !== "check" && failAt !== "erase" }),
  };
}

/** A played run's state at `elapsed` ms, as a real run's status() answers it. */
export function stateAt(run, elapsed) {
  const done = elapsed >= run.end;
  return {
    status: done ? run.status : "running",
    startedAt: run.startedAt,
    endedAt: done ? run.startedAt + run.end : null,
    lines: run.timeline.filter(([t]) => t <= elapsed).map(([, line]) => line),
    steps: stepsFor(run.erase),
    result:
      done && run.status === "succeeded"
        ? {
            issuer: `https://iterate.${run.zone}`,
            commit: COMMIT,
            replaced: run.replaced,
          }
        : null,
    ...(run.erase && { erase: true, erased: done && run.erased }),
    ...(done && run.failedAt && { failedAt: run.failedAt }),
    ...(done && run.keyOutside && { keyOutside: true }),
  };
}