iterate.com / cloud

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

cloud / internal-packages / installer / worker / deployments.jsmain at aacbc74

// deployments.js — "YOUR DEPLOYMENTS": every deployment of iterate in the Cloudflare accounts a
// person connected, for the page (src/Deployments.tsx) and the sidebar (src/CloudNav.tsx).
//
// THE CLOUD STORES NOTHING FOR THIS. Each answer is read when it is asked:
//   which deployments   the person's own account, with the token of their session: its Workers
//                       named `iterate-<name>-boundary` or `-ingress` (a stack's boundary), or
//                       its main Worker alone (a stack that is incomplete), matched to its zones.
//                       THE STACK OF A ZONE IS THE ONE THAT SERVES IT (`servedBy`): its name is
//                       read from the zone's routes, whatever it is. A stack that somebody
//                       deployed from a computer has the name they chose (`jeeves` on
//                       templestein.family), not the one this Cloud makes from the zone.
//   whether it answers  the deployment itself: its issuer's metadata, and its Dash, where the
//                       onboarding chat is
//   what it runs        the commit of iterate that its boundary Worker names in a tag (a deploy
//                       from 12 November 2026 on writes it: core/alchemy/src/stack.ts), else the
//                       record of the deploy run this Cloud made for it (deploy-run.js), if any
//   the shared apps     the Routes of iterate's clients (internal-packages/cloud-clients)
// A domain is looked up in the Cloud's own rows (the enrolment, the Routes, the run) ONLY when the
// session's token has just listed its zone in that account, never because a request names it.

import { keptOf, namesOf, outsideOf } from "../container/takeover.mjs";
import { cloudflareTokenCurrent } from "./scopes.js";

/** A stack's boundary Worker, which serves its domain: `-ingress` is its name from before the
 *  rename. */
const INGRESS = /^iterate-(.+)-(?:ingress|boundary)$/;
/** A stack's main Worker, under both of its names. With no boundary Worker beside it, the stack
 *  is incomplete: a deploy or an erase that did not finish left it. */
const MAIN = /^iterate-(.+)-(?:mind|project)$/;
/** The Workers that only a stack from before the rename has. */
const OLDER = /^iterate-(.+)-(?:ingress|project)$/;
/** A stack's boundary Worker under its name of today: the one a deploy tags with its commit. */
const BOUNDARY = /^iterate-(.+)-boundary$/;
/** The tag that names the commit of iterate a stack runs (core/alchemy/src/stack.ts `COMMIT_TAG`). */
const COMMIT_TAG = /^iterate-commit:([0-9a-f]{40})$/;
/** A stack's telemetry Worker: the stack keeps its own events, logs and traces. */
const TELEMETRY = /^iterate-(.+)-telemetry$/;
/** A stack's name (core/alchemy/src/config.ts): what this Cloud passes on as one. */
export const STACK_NAME = /^[a-z][a-z0-9-]{0,39}$/;
/** A person with more accounts or stacks than this sees the first ones, and is told so. */
const MOST_ACCOUNTS = 10;
const MOST_DEPLOYMENTS = 40;
/** The routes of this many zones of one account are read, the likely ones first. */
const MOST_ZONES = 40;
/** This many answers of an account's zones are read: 50 zones in each. */
const MOST_ZONE_PAGES = 40;

/**
 * Every zone of an account, by name: `{ zones, errors }`. Cloudflare gives 50 at most in one
 * answer, and its first answer says how many answers there are. The others are asked together:
 * an account with 440 domains is 9 answers, and one after the other they took 4 to 9 seconds.
 * An answer that does not say how many there are is followed page by page.
 */
export async function zonesOf(cf, accountId) {
  const page = (number) =>
    cf("GET", `/zones?account.id=${accountId}&per_page=50&order=name&page=${number}`);
  const answers = [await page(1)];
  const pages = Math.min(Number(answers[0].result_info?.total_pages) || 0, MOST_ZONE_PAGES);
  if (pages > 1)
    answers.push(
      ...(await Promise.all(Array.from({ length: pages - 1 }, (_, at) => page(at + 2)))),
    );
  else if (pages === 0)
    while ((answers.at(-1).result || []).length === 50 && answers.length < MOST_ZONE_PAGES)
      answers.push(await page(answers.length + 1));
  return {
    zones: answers.flatMap((answer) => answer.result || []),
    errors: answers.flatMap((answer) => answer.errors || []),
  };
}

/** The commit of iterate that each stack's boundary Worker names, by the stack's name, from an
 *  account's list of Workers. A Worker with no such tag, or with two, names none. */
export function taggedCommits(workers) {
  return new Map(
    (workers || []).flatMap((worker) => {
      const name = BOUNDARY.exec(String(worker.id || ""))?.[1];
      const named = (worker.tags || []).flatMap((tag) => COMMIT_TAG.exec(String(tag))?.[1] || []);
      return name && named.length === 1 ? [[name, named[0]]] : [];
    }),
  );
}

/**
 * The name of the stack that serves `zone`, from the zone's Workers routes; null when no stack
 * does. The Worker on `iterate.<zone>/*` says it (a stack that serves its platform's names
 * alone), else the one on `*.<zone>/*` (a stack that serves every name): the same order as
 * Cloudflare's, where the longer pattern wins. A Worker of another name there is nobody's stack.
 */
export function servedBy(zone, routes) {
  for (const pattern of [`iterate.${zone}/*`, `*.${zone}/*`]) {
    const route = (routes || []).find((r) => r.pattern === pattern);
    if (!route) continue;
    const name = INGRESS.exec(String(route.script || ""))?.[1];
    return name && STACK_NAME.test(name) ? name : null;
  }
  return null;
}

/** The Workers that are not the stack's and that the zone serves, by a route or a custom domain:
 *  the erase stops at each (container/takeover.mjs `outsideOf`). */
function othersOn(zoneId, name, routes, domains) {
  const names = namesOf(name);
  return [
    ...new Set([
      ...(routes || []).map((r) => r.script),
      ...(domains || []).filter((d) => d.zone_id === zoneId).map((d) => d.service),
    ]),
  ].filter((worker) => outsideOf(names, worker));
}
/** A deployment that does not answer in this time does not hold the page. */
const LOOK_MS = 4000;

/** One GET of a deployment's own address, which never throws: `{ status, location, authenticate }`. */
async function look(host, path) {
  try {
    const answer = await fetch(`https://${host}${path}`, {
      redirect: "manual",
      headers: { accept: "text/html" },
      signal: AbortSignal.timeout(LOOK_MS),
    });
    await answer.body?.cancel();
    return {
      status: answer.status,
      location: answer.headers.get("location") || "",
      authenticate: answer.headers.get("www-authenticate") || "",
    };
  } catch {
    return { status: 0, location: "", authenticate: "" };
  }
}

/** What the deployment at `domain` answers now: as an issuer (what a deploy run waits for), and
 *  its Dash, where the onboarding chat is (`onboarding`). A signed-out visit to a mounted app is
 *  sent to the deployment's own sign-in; a mind with no such app answers 404. On the pretend deployment nothing is on the
 *  internet: `standIn(host)` asks the pretend Cloudflare whether its stand-in is there. */
async function answersOf(domain, standIn) {
  if (standIn) {
    const [answers, onboarding] = await Promise.all([
      standIn(`iterate.${domain}`),
      standIn(`dash.${domain}`),
    ]);
    return { answers, onboarding };
  }
  const [issuer, onboarding] = await Promise.all([
    look(`iterate.${domain}`, "/.well-known/oauth-authorization-server"),
    look(`dash.${domain}`, "/"),
  ]);
  return {
    answers: issuer.status === 200,
    onboarding:
      onboarding.status === 302 &&
      onboarding.location.startsWith(`https://iterate.${domain}/oauth2/auth`),
  };
}

/**
 * Which of the pages that the person's page links to answer NOW at `domain`, for a deployment
 * whose run kept no record of them (a run from before container/check-result.sh looked): the same
 * questions as that check, asked from here. `{ <id>: "works" | "missing" }`, by the ids of
 * src/deploy-steps.ts `PAGES`. On the pretend deployment a host's stand-in answers for its pages.
 */
export async function pagesNow(domain, standIn) {
  const site = `https://iterate.${domain}`;
  const said = (works) => (works ? "works" : "missing");
  if (standIn) {
    const [issuer, dash] = await Promise.all(
      ["iterate", "dash"].map((host) => standIn(`${host}.${domain}`)),
    );
    return {
      keys: said(issuer),
      members: said(issuer),
      "self-test": said(issuer),
      mcp: said(issuer),
      dash: said(dash),
    };
  }
  const [keys, members, selfTest, mcp, dash] = await Promise.all([
    look(`iterate.${domain}`, "/keys"),
    look(`iterate.${domain}`, "/members"),
    look(`iterate.${domain}`, "/self-test"),
    look(`iterate.${domain}`, "/mcp"),
    look(`dash.${domain}`, "/"),
  ]);
  // a page of iterate.<domain> that asks for a sign-in first sends a browser to its sign-in
  const asksSignIn = (answer) =>
    (answer.status === 302 || answer.status === 303) &&
    answer.location.startsWith(`${site}/sign-in`);
  return {
    keys: said(asksSignIn(keys)),
    members: said(asksSignIn(members)),
    "self-test": said(asksSignIn(selfTest)),
    mcp: said(mcp.status === 401 && /^bearer\b/i.test(mcp.authenticate)),
    // the Dash, an app of the config repo, sends a signed-out browser to iterate.<domain>'s sign-in
    dash: said(dash.status === 302 && dash.location.startsWith(`${site}/oauth2/auth`)),
  };
}

/**
 * The deployments in `accounts`.
 *   cf(method, path)   one call to Cloudflare's API with the session's token (index.js `cf`)
 *   nameOf(zone)       the name this Cloud gives a new stack, from its zone (index.js)
 *   host               where the page is served: its own zone is never erased
 *   env                DEPLOYER (the runs), SESSIONS (the rows), ROUTES (the clients' routes, if bound)
 *   commits            the commits of iterate this Cloud has (stack-commits.js): `{ own, all }`
 *   standIn(host)      the pretend deployment alone: whether a host's stand-in is there
 *   timing             filled with how long each part took and how much it read, for the
 *                      Worker's log: counts and milliseconds alone, no name and no id
 *
 * WHAT IS ASKED TOGETHER. An account's Workers, its zones and its custom domains do not wait for
 * each other, and neither do the routes of its zones: one after the other, an account with 440
 * domains and a stack with a name of its own held the page for 12 to 18 seconds.
 */
export async function deploymentsOf({
  cf,
  nameOf,
  host = "",
  accounts,
  env,
  commits = { own: null, all: new Set() },
  standIn,
  timing = /** @type {{ accounts: Record<string, number>[] }} */ ({ accounts: [] }),
}) {
  const began = Date.now();
  const notes = [];
  if (accounts.length > MOST_ACCOUNTS)
    notes.push(`You have ${accounts.length} accounts: the first ${MOST_ACCOUNTS} are shown.`);
  const perAccount = await Promise.all(
    accounts.slice(0, MOST_ACCOUNTS).map(async (account) => {
      // asked now, read below when the account holds a stack: a refusal is thrown there, not here
      const zonesAsked = zonesOf(cf, account.id).then((listed) => ({
        ...listed,
        ms: Date.now() - began,
      }));
      const domainsAsked = cf("GET", `/accounts/${account.id}/workers/domains`);
      zonesAsked.catch(() => {});
      domainsAsked.catch(() => {});
      const scripts = await cf("GET", `/accounts/${account.id}/workers/scripts`);
      const took = { workers: (scripts.result || []).length, workersMs: Date.now() - began };
      timing.accounts.push(took);
      if (!scripts.success) {
        notes.push(`Cloudflare did not list the Workers of ${account.name}.`);
        return [];
      }
      const named = (pattern) =>
        (scripts.result || []).flatMap((worker) => {
          const name = pattern.exec(String(worker.id || ""))?.[1];
          return name ? [[name, worker.modified_on || null]] : [];
        });
      // a stack with a boundary Worker, and one that has its main Worker alone
      const whole = new Map(named(INGRESS));
      const stacks = new Map([...named(MAIN), ...whole]);
      if (stacks.size === 0) return [];
      // a stack from before the rename: the deploy run stops at one (container/run.sh
      // `not_older_stack`, by the same two names), so the page offers no update of it
      const older = new Set(named(OLDER).map(([name]) => name));
      const telemetry = new Set(named(TELEMETRY).map(([name]) => name));
      const tagged = taggedCommits(scripts.result);
      const { zones, ms: zonesMs } = await zonesAsked;
      Object.assign(took, { stacks: stacks.size, zones: zones.length, zonesMs });
      // The routes of a zone say which stack serves it, and which other Workers it serves.
      // An account can hold hundreds of zones, and one call reads the routes of one zone. So the
      // stacks say where to look: first the zones whose own name makes a stack's name, and those
      // that share a word with one (`iterate` and iterate.com). The other zones are read only
      // while a stack is not found on a zone, and MOST_ZONES at most in all.
      const likely = (zone) => {
        if (stacks.has(nameOf(zone.name))) return 0;
        const word = zone.name.split(".")[0];
        return [...stacks.keys()].some((name) => name.includes(word) || word.includes(name))
          ? 1
          : 2;
      };
      const sorted = [...zones].sort((a, b) => likely(a) - likely(b)).slice(0, MOST_ZONES);
      const routesOf = new Map();
      // all of a list together: MOST_ZONES at most, and the Worker itself holds what is over
      // its six connections
      const read = (list) =>
        Promise.all(
          list.map(async (zone) => {
            const answer = await cf("GET", `/zones/${zone.id}/workers/routes`);
            routesOf.set(zone.id, answer.success ? answer.result || [] : null);
          }),
        );
      /** The stacks with a boundary Worker that no zone read so far is served by. */
      const unplaced = () => {
        const placed = new Set(
          sorted.map((zone) => routesOf.has(zone.id) && servedBy(zone.name, routesOf.get(zone.id))),
        );
        return [...whole.keys()].filter((name) => !placed.has(name));
      };
      await read(sorted.filter((zone) => likely(zone) < 2));
      if (unplaced().length > 0) await read(sorted.filter((zone) => !routesOf.has(zone.id)));
      const looked = sorted.filter((zone) => routesOf.has(zone.id));
      // said only when it matters: a stack is in the account, and its domain was not found
      const lost = zones.length > sorted.length ? unplaced() : [];
      if (lost.length > 0)
        notes.push(
          `${account.name} has ${zones.length} domains, and iterate looked at ${looked.length} of them. It did not find the domain of ${
            lost.length === 1 ? `the deployment ${lost[0]}` : `${lost.length} deployments`
          }.`,
        );
      Object.assign(took, { routes: routesOf.size, routesMs: Date.now() - began });
      const domains = await domainsAsked;
      took.domainsMs = Date.now() - began;
      const served = new Map(
        looked.flatMap((zone) => {
          const name = servedBy(zone.name, routesOf.get(zone.id));
          return name && stacks.has(name) ? [[zone.id, name]] : [];
        }),
      );
      const serving = new Set(served.values());
      return zones.flatMap((zone) => {
        // the stack that serves the zone; else the stack with the zone's name that serves no
        // other zone: parts of one that a deploy or an erase left
        const guess = nameOf(zone.name);
        const name = served.get(zone.id) || (stacks.has(guess) && !serving.has(guess) && guess);
        if (!name) return [];
        const routes = routesOf.get(zone.id);
        const others = othersOn(zone.id, name, routes, domains.result);
        return [
          {
            account,
            domain: zone.name,
            zone: {
              id: zone.id,
              name: zone.name,
              status: zone.status,
              nameServers: zone.name_servers || [],
            },
            name,
            changedAt: stacks.get(name),
            older: older.has(name),
            telemetry: telemetry.has(name),
            tagged: tagged.get(name) || null,
            incomplete: !whole.has(name),
            // its boundary Worker is on the zone's routes now
            serves: served.has(zone.id),
            // why no erase is offered: the erase page and the run refuse the same (takeover.mjs)
            noErase:
              keptOf(zone.name, host) ||
              (others.length > 0
                ? `${zone.name} also serves ${
                    others.length === 1 ? `the Worker ${others[0]}` : `${others.length} Workers`
                  } that ${others.length === 1 ? "is" : "are"} not iterate's. iterate never erases a domain that serves another Worker.`
                : null),
          },
        ];
      });
    }),
  );
  const found = perAccount.flat().sort((a, b) => a.domain.localeCompare(b.domain));
  if (found.length > MOST_DEPLOYMENTS)
    notes.push(`You have ${found.length} deployments: the first ${MOST_DEPLOYMENTS} are shown.`);
  const listedMs = Date.now() - began;
  const routes = env.ROUTES?.get(env.ROUTES.idFromName("routes"));
  const deployments = await Promise.all(
    found
      .slice(0, MOST_DEPLOYMENTS)
      .map(
        async ({
          account,
          domain,
          zone,
          name,
          changedAt,
          older,
          telemetry,
          tagged,
          incomplete,
          serves,
          noErase,
        }) => {
          const [live, run, started, enrolled, apps] = await Promise.all([
            answersOf(domain, standIn),
            env.DEPLOYER.getByName(`${account.id}:${name}`)
              .status()
              .catch(() => null),
            env.SESSIONS.get(`dep:${account.id}:${name}`),
            env.SESSIONS.get(`enrolled:${domain}`),
            routes ? routes.clientsOf(domain).catch(() => null) : null,
          ]);
          const owner = (started && JSON.parse(started).owner) || null;
          // The same order as the run's own check (container/run.sh `not_unknown_stack`): what the
          // stack's Worker says, else what this Cloud's last run that worked deployed there.
          const commit = tagged || run?.result?.commit || null;
          const runs = commit || run?.recorded || null;
          const foreign =
            runs && commits.own && !commits.all.has(runs) ? { runs, cloud: commits.own } : null;
          // what stops every update from here, whoever deployed the stack
          const sound = !older && !incomplete && !run?.keyOutside;
          return {
            account,
            domain,
            zone,
            name,
            ...live,
            // when Cloudflare says the stack's boundary last changed: a deploy from anywhere
            changedAt,
            // the run this Cloud made: none for a stack somebody deployed another way
            run:
              run && run.status !== "idle"
                ? {
                    status: run.status,
                    endedAt: run.endedAt || null,
                    commit: run.result?.commit || null,
                    // each Worker's version before and after that run: the proof of an update
                    versions: run.result?.versions || null,
                    // the last deploy from here made or kept the mind's Cloudflare connection
                    cloudflareToken: run.connection === true,
                    // and its token is of this release's edition: else an update narrows it
                    cloudflareTokenCurrent: cloudflareTokenCurrent(run),
                  }
                : null,
            // which commit of iterate it runs, when its Worker or this Cloud's record says it
            commit,
            // it runs an iterate that this Cloud does not have: the card says so, and offers the
            // update only as "Update anyway" (container/run.sh `not_unknown_stack`)
            foreign,
            // whatever this Cloud's last run there said: "Update anyway" is then the one way on
            // that is not an erase
            replaceable: sound && !!foreign && serves,
            // from before the rename: it cannot be updated in place, only erased and replaced
            older,
            // it has its telemetry Worker: its own warehouse of events, logs and traces is on
            telemetry,
            // parts of a stack and no Worker that serves the domain: only the erase is offered
            incomplete,
            // An update from here: of a stack this Cloud deployed (the record of the first deploy
            // says who signs in to it), and of a stack that somebody deployed another way and that
            // serves the domain. Such a stack keeps its own config, and the run deploys from it.
            updatable: sound && (owner ? run?.status === "succeeded" : serves),
            // the stack's vault key is not in Cloudflare: a run from here found that and stopped
            // (container/run.sh `stack_updatable`), so the page offers no update
            keyOutside: !!run?.keyOutside,
            noErase,
            owner,
            enrolled: !!enrolled,
            // which of iterate's shared apps deliver to it, and for how many accounts at each
            apps: apps || {},
          };
        },
      ),
  );
  // every "Ms" is from the start of the read: the parts overlap, so they are not to be added
  Object.assign(timing, {
    deployments: deployments.length,
    listedMs,
    totalMs: Date.now() - began,
  });
  return { deployments, notes };
}