iterate.com / cloud

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

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

// installation-pretend.js — THE PHASES OF A CHAT INSTALLATION, ACTED OUT (installation.js), for the
// pretend Cloud (pretend-deployer.js) and the tests: the same lines as a real phase, on a clock,
// with nothing deployed. The deploy phase is the pretend run of the wizard (pretend-run.js, its
// domain's name sets off the same awkward cases), up to its own "forget" step: the installation
// gives up its access itself. Like the pretend deployer it tells the pretend Cloudflare, with the
// person's token, when the deployment will "exist", and it keeps no token.
//
// A phase's state is all in what `launch` answers (the installation stores it in `running`), so a
// restart of the object loses nothing of it.
import { COMMIT, plan } from "./pretend-run.js";

const PREP_MS = 6_000;
const EARLY_MS = 8_000;

/** @param {{ fetch: typeof fetch, api: string, site: string, now?: () => number }} parts
 *  `api`: the pretend Cloudflare's API, `site`: its address (for `/_pretend/deployed`). */
export function pretendRunner({ fetch: fetcher, api, site, now = Date.now }) {
  const call = async (token, method, path, body) => {
    const answer = await fetcher(`${api}${path}`, {
      method,
      headers: {
        authorization: `Bearer ${token}`,
        ...(body && { "content-type": "application/json" }),
      },
      body: body ? JSON.stringify(body) : undefined,
    });
    return answer.json().catch(() => ({ success: false }));
  };
  return {
    async launch(phase, { env, files, zone }) {
      const token = env.CLOUDFLARE_API_TOKEN;
      const account = env.CLOUDFLARE_ACCOUNT_ID;
      const name = env.ITERATE_NAME;
      if (phase === "prep") {
        const lines = [`stack ${COMMIT}`, "== step prep"];
        const checked = await call(token, "GET", `/accounts/${account}`);
        if (!checked.success)
          return {
            timeline: [[1000, `Cloudflare refused the account ${account}.`]],
            exit: "1",
            end: 1500,
          };
        lines.push(`account: ${checked.result?.name || account}`);
        const sub = await call(token, "GET", `/accounts/${account}/workers/subdomain`);
        if (sub.success) lines.push(`workers.dev: ${sub.result.subdomain}.workers.dev`);
        else {
          const derived = String(env.ITERATE_WORKERS_DEV_NAMES || "")
            .split(" ")
            .filter(Boolean);
          const names = [...derived, name];
          let made = null;
          for (const subdomain of names) {
            // as run.sh: a derived name is checked first, and skipped when Cloudflare says taken
            if (derived.includes(subdomain)) {
              const free = await call(
                token,
                "GET",
                `/accounts/${account}/workers/subdomains/${subdomain}`,
              );
              if (JSON.stringify(free.errors || []).includes("10031")) continue;
            }
            const answer = await call(token, "PUT", `/accounts/${account}/workers/subdomain`, {
              subdomain,
            });
            if (answer.success) {
              made = subdomain;
              break;
            }
          }
          lines.push(
            made
              ? `workers.dev: made ${made}.workers.dev for the account.`
              : `Note: the account has no workers.dev name, and ${names.join(", ")} are taken: the deploy asks again.`,
          );
        }
        lines.push(`The state store iterate-${name}-state answers.`, "Built the mind's Worker.");
        return {
          timeline: lines.map((line, i) => [Math.round(((i + 1) / lines.length) * PREP_MS), line]),
          exit: "0",
          end: PREP_MS + 200,
        };
      }
      if (phase === "early") {
        // as run.sh `early`: the config says what this deploy leaves out
        const config = JSON.parse(files["/work/mind.config.json"]);
        const n = `iterate-${name}`;
        const lines = [
          `stack ${COMMIT}`,
          "== step early",
          `${config.cloudflarePlan === "free" ? "The stack before its domain, on what a Free account takes" : "The stack before its domain, with Workers Paid and R2"}, and with no sandboxes yet (mind.containers: false).`,
          `+ ${n}-state  Cloudflare.D1Database  created`,
          `+ ${n}-auth-db  Cloudflare.D1Database  created`,
          `+ ${n}-secrets  Cloudflare.KVNamespace  created`,
          `+ ${n}-auth  Cloudflare.Worker  uploaded`,
          `+ ${n}-mind  Cloudflare.Worker  uploaded`,
          `+ ${n}-boundary  Cloudflare.Worker  uploaded`,
          `The stack ${n} is deployed before its domain: the deploy at the domain gives it the rest.`,
        ];
        return {
          timeline: lines.map((line, i) => [Math.round(((i + 1) / lines.length) * EARLY_MS), line]),
          exit: "0",
          end: EARLY_MS + 200,
        };
      }
      // the deploy: the wizard's pretend run, without its last step
      const attempt = Number(env.ITERATE_ATTEMPT || 1);
      const played = plan(
        { zone, name, erase: false, anyway: undefined, runs: undefined },
        attempt,
      );
      const forget = played.timeline.findIndex(([, line]) => line === "== step forget");
      const timeline = played.timeline.slice(0, forget);
      const end = (timeline.at(-1)?.[0] ?? 0) + 300;
      const worked = played.deployed && played.status !== "failed";
      if (played.deployed) {
        await fetcher(`${site}/_pretend/deployed`, {
          method: "POST",
          headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
          body: JSON.stringify({ account, name, domain: zone, at: now() + end, commit: COMMIT }),
        });
      }
      const lines = env.ITERATE_CLOUDFLARE_TOKEN
        ? [...timeline, [end - 100, "cloudflare-connection on"]]
        : timeline;
      return { timeline: lines, exit: worked ? "0" : "1", end };
    },
    async poll(_phase, running) {
      const elapsed = now() - running.startedAt;
      const lines = running.timeline.filter(([t]) => t <= elapsed).map(([, line]) => line);
      return elapsed >= running.end
        ? { done: true, exit: running.exit, lines }
        : { done: false, lines };
    },
    async stop() {},
  };
}