iterate.com / cloud

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

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

// deploy-run.js — ONE DEPLOY RUN OF A MIND'S STACK: a Durable Object with its own container
// (container/Dockerfile, which holds the stack built), one per `<accountId>:<name>`. It writes the
// stack's config for a first deploy (an update deploys from the config the stack keeps beside its
// state), runs /stack/run.sh detached, and answers the run's state from its log. An alarm
// keeps it awake while the run lives, so a closed page does not end it.
//
// iterate's Cloud keeps no Cloudflare token. The person's token (about an hour, no refresh token)
// is in this object's memory and in the run's process environment, and nowhere else: not in
// storage, not in a file, not in a log line (run.sh writes `[token]` in its place). When the run
// ends, on success and on failure alike, this object revokes the token and destroys the container.
//
// A first deploy and a recovery run (`recoverOwner`) also make the owner's ticket (first-owner.js).
// The ticket is in this object's memory alone. The run gets its hash, so no log can hold it, and the person's page gets
// the ticket once.
import { DurableObject } from "cloudflare:workers";
import { Files } from "@cloudflare/sandbox";
import { claimIn, forgetLinesOf, giveUp } from "./cloudflare-access.js";
import { firstOwnerTicket, withTicket } from "./first-owner.js";
import { INSTALL_OPS, Installation } from "./installation.js";
import { keptLines } from "./run-log.js";
import { connectionAfter } from "./scopes.js";
import { configOf } from "./stack-config.js";

const LOG = "/work/deploy.log";
const STARTING = "Starting the run's container.";
// The environment of the run's process. exec's `env` may replace the image's: the run needs these.
const BASE_ENV = {
  PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  HOME: "/root",
};

/** How run.sh says that a stack's vault key is not in Cloudflare (its `updatable_from_here`). */
const KEY_OUTSIDE = "Stopped: This deployment keeps its vault key outside Cloudflare.";

/** The steps of a run, in order. A log line `== step <id>` starts one. */
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" },
];
/** "Erase and replace" has one step more, after the check. */
const ERASE_STEP = { id: "erase", label: "Erase the domain and the earlier iterate" };

/** What this object keeps in its storage, by key: the descriptions `kept()` shows. */
const RECORDS = {
  "claim:":
    "That the token of one sign-in is spoken for, and since when: a deploy run took it, or a sign-out revoked it. No token. Dropped after two hours.",
  ...Installation.RECORDS,
  state:
    "The run: its status, start and end, the account id, the zone, the deployment's name, whether it erases the domain first, when the access to Cloudflare ends, the last 400 lines of its log and, from before them, each step's first line, each note and what an erase said, the commit that the last run that worked deployed, its result (the stack's commit, the commit it replaced when the person pressed “Update anyway”, and the version of each of its Workers before and after), and how the access was given up: the status of the revoke and the status the token got after it.",
};

const utc = (ms) => `${new Date(ms).toISOString().slice(0, 16).replace("T", " ")} UTC`;

export class Deployer extends DurableObject {
  /** The person's Cloudflare token, in memory only, for the revoke at the run's end. */
  #token = null;
  /** The first owner's ticket (first-owner.js), in memory only, until the page was given it.
   *  @type {Awaited<ReturnType<typeof firstOwnerTicket>> | null} */
  #first = null;
  /** The run's end, while it is being finished: two status() calls finish it once.
   *  @type {Promise<any> | null} */
  #finishing = null;
  /** The run's start, while its container comes up: status() then reads no log yet.
   *  @type {Promise<void> | null} */
  #launching = null;

  /** A chat installation (installation.js) lives in an object of its own, named `inst:<id>`, with
   *  the same container as a run: its phases run /stack/run.sh too. Made at the first call. */
  /** @type {Installation | null} */
  #installation = null;
  /** A phase's start while its container comes up, and why it did not start.
   *  @type {Promise<unknown> | null} */
  #phaseLaunch = null;
  /** @type {string | null} */
  #phaseFailed = null;

  /** @returns {Installation} */
  installation() {
    this.#installation ||= new Installation({
      storage: this.ctx.storage,
      env: this.env,
      runner: this.phaseRunner(),
      fetch: (input, init) => fetch(input, init),
    });
    return /** @type {Installation} */ (this.#installation);
  }

  /** The operations of service.js and index.js on an installation, by name. */
  install(op, args) {
    const installation = this.installation();
    if (!INSTALL_OPS.includes(op)) throw new Error(`no such operation: ${op}`);
    return installation[op](args);
  }

  /** The installation's phases in this object's container: each runs /stack/run.sh with
   *  ITERATE_PHASE, detached, and writes its own log. */
  phaseRunner() {
    const log = (phase) => `/work/phase-${phase}.log`;
    return {
      launch: async (phase, { env, files }) => {
        this.#phaseFailed = null;
        const started = (async () => {
          const c = this.container();
          await this.ready(c);
          for (const [path, text] of Object.entries(files))
            await new Files(c).writeFile(path, text);
          const command = `rm -f ${log(phase)}; setsid nohup bash /stack/run.sh > ${log(phase)} 2>&1 < /dev/null &`;
          const vars = Object.fromEntries(Object.entries(env).filter(([, v]) => v));
          await (await c.exec(["bash", "-c", command], { env: { ...BASE_ENV, ...vars } })).output();
        })();
        this.#phaseLaunch = started
          .catch((error) => (this.#phaseFailed = String(error?.message || error)))
          .finally(() => (this.#phaseLaunch = null));
        this.ctx.waitUntil(this.#phaseLaunch);
        return {};
      },
      poll: async (phase) => {
        if (this.#phaseLaunch) return { done: false, lines: [STARTING] };
        if (this.#phaseFailed)
          return {
            done: true,
            exit: "1",
            lines: [`The phase did not start: ${this.#phaseFailed}.`],
          };
        if (!this.ctx.container?.running)
          return {
            done: true,
            exit: "1",
            lines: ["The run's container stopped before the phase ended."],
          };
        try {
          const res = await new Files(this.container()).readFile(log(phase));
          if (!res.ok)
            return {
              done: true,
              exit: "1",
              lines: ["The phase lost its start: this object restarted."],
            };
          const lines = (await res.text()).split("\n").filter(Boolean);
          const exit = lines
            .map((l) => /^__EXIT__:(\d+)/.exec(l)?.[1])
            .filter(Boolean)
            .at(-1);
          const shown = lines.filter((l) => !l.startsWith("__EXIT__"));
          return exit
            ? { done: true, exit, lines: shown }
            : { done: false, lines: keptLines(shown) };
        } catch (error) {
          return {
            done: false,
            lines: [`(the container isn't answering: ${String(error?.message || error)})`],
          };
        }
      },
      stop: async () => {
        if (!this.ctx.container?.running) return;
        try {
          await this.ctx.container.destroy();
        } catch {
          // the next look sees a container that is still up, and stops it again
        }
      },
    };
  }

  container() {
    const c = this.ctx.container;
    if (!c) throw new Error("the container binding is not configured");
    // one image ("image" in wrangler) starts by default; a named one ("images") is chosen
    if (!c.running)
      c.start(
        c.images?.sandbox
          ? { image: c.images.sandbox, enableInternet: true }
          : { enableInternet: true },
      );
    return c;
  }

  /** Waits until the container answers, ten minutes at most: its first start pulls the image,
   *  which holds the whole stack and can take minutes. */
  async ready(c) {
    for (let i = 0; i < 300; i++) {
      try {
        await (await c.exec(["true"])).output();
        return;
      } catch {
        await new Promise((r) => setTimeout(r, 2000));
      }
    }
    throw new Error("the container did not start within ten minutes");
  }

  /** Starts a run and answers its state at once: the container comes up behind the answer
   *  (`launch`), since that can take minutes. A run already running is left alone. */
  async start(args) {
    const state = /** @type {any} */ (await this.ctx.storage.get("state"));
    // a run that already runs is not this caller's: `began` says so, and the caller then keeps
    // nothing of it (index.js: no row with its name, and so no first owner's ticket)
    if (state?.status === "running") return { began: false, state: await this.look() };
    const { accountId, zone, name, token, tokenExpiresAt } = args;
    this.#token = token;
    // What this Cloud's last run that worked deployed there, for a stack that does not say
    // itself what it runs. A run that fails keeps it (`recorded`): a second press after a refusal
    // meets the same refusal. An erase ends it: what it named is gone.
    const recorded = (!args.erase && (state?.result?.commit || state?.recorded)) || undefined;
    // Whether the stack's mind has its Cloudflare connection, as the last deploy from here said
    // (run.sh prints it after a deploy that worked). A run that does not get that far keeps it.
    const connection = args.erase ? undefined : state?.connection;
    const connectionEdition = args.erase ? undefined : state?.connectionEdition;
    const next = {
      status: "running",
      startedAt: Date.now(),
      accountId,
      zone,
      name,
      tokenExpiresAt,
      ...(args.erase && { erase: true }),
      recorded,
      connection,
      connectionEdition,
    };
    await this.ctx.storage.put("state", next);
    await this.ctx.storage.setAlarm(Date.now() + 10_000);
    this.#launching = this.launch({ ...args, recorded })
      .catch((error) =>
        this.finish(next, [`The run did not start: ${String(error?.message || error)}.`], "1"),
      )
      .finally(() => (this.#launching = null));
    this.ctx.waitUntil(this.#launching);
    return { began: true, state: answerOf({ ...next, lines: [STARTING] }) };
  }

  /** Brings the container up, writes the stack's config for a first deploy, and runs /stack/run.sh
   *  detached with the token in its environment alone: not in the command, an argument or a file.
   *  A first deploy also gets the hash of the owner's ticket there, and so does an update that the
   *  owner asked for to get back in (`recoverOwner`: their address). Any other update gets none,
   *  and the stack then drops what it had. With `erase`, the name of the list the person agreed
   *  to, the run first erases the domain and the earlier iterate (container/takeover.mjs).
   *  `recorded` and `anyway` are for the run's check of the stack's own commit (container/run.sh
   *  `not_unknown_stack`): what this Cloud's last run deployed there, and the commit that the
   *  person agreed to replace although this Cloud does not have it. */
  async launch(args) {
    const { accountId, zone, zoneId, name, token } = args;
    const c = this.container();
    await this.ready(c);
    // The wizard's deploy pushes iterate's image itself (container/run.sh). The stack holds the
    // image's pin, so the config names it by the older word, which the stack reads as
    // `images: { "iterate-dev-image": { image } }` at that pin (core/alchemy/src/config.ts).
    const config = configOf({ ...args, mind: { sandboxImage: "published" } });
    if (config)
      await new Files(c).writeFile(
        "/work/mind.config.json",
        `${JSON.stringify(config, null, 2)}\n`,
      );
    const owner = config ? args.ownerEmails[0] : args.recoverOwner;
    this.#first = owner ? await firstOwnerTicket(owner) : null;
    const env = {
      ...BASE_ENV,
      CLOUDFLARE_API_TOKEN: token,
      CLOUDFLARE_ACCOUNT_ID: accountId,
      ITERATE_ZONE: zone,
      ITERATE_ZONE_ID: zoneId,
      ITERATE_NAME: name,
      ...(this.#first && { ITERATE_FIRST_OWNER_TICKET: this.#first.variable }),
      // oxlint-disable-next-line iterate/simple-truthiness-check -- a variable of a process: one with no value must not be set at all
      ...(args.erase && { ITERATE_ERASE: args.erase }),
      // the run may turn the stack's telemetry on: the access has the scopes for it
      ...(args.telemetry && { ITERATE_TELEMETRY: "1" }),
      // and may give its mind a Cloudflare connection: the access may make its API token
      ...(args.cloudflareToken && { ITERATE_CLOUDFLARE_TOKEN: "1" }),
      // oxlint-disable-next-line iterate/simple-truthiness-check -- a variable of a process: one with no value must not be set at all
      ...(args.recorded && { ITERATE_RECORD_COMMIT: args.recorded }),
      // oxlint-disable-next-line iterate/simple-truthiness-check -- a variable of a process: one with no value must not be set at all
      ...(args.anyway && { ITERATE_UPDATE_ANYWAY: args.anyway }),
    };
    const command = `rm -f ${LOG}; setsid nohup bash /stack/run.sh > ${LOG} 2>&1 < /dev/null &`;
    await (await c.exec(["bash", "-c", command], { env })).output();
  }

  /** The run's state: `{ status, startedAt, endedAt, lines, steps, result }`, `status` one of
   *  idle, running, succeeded and failed. A run of "Erase and replace" also says `erase: true`
   *  and, at its end, `erased`: whether the erase was done. A run that gave a token up says
   *  `forgot`: `{ revoke, probe, works }` (cloudflare-access.js `giveUp`), and `failedAt: "forget"`
   *  when that is all that failed. `shown`: the answer goes to the person's page. The first
   *  such answer of a first deploy that succeeded carries the first owner's ticket
   *  (`result.firstOwnerTicket`, `result.firstOwnerTicketEnds`), and then this object has forgotten it. */
  async status(shown = false) {
    const answer = await this.look();
    if (!shown || answer.status !== "succeeded" || !this.#first) return answer;
    const first = this.#first;
    this.#first = null;
    return withTicket(answer, first);
  }

  /** Reads the run's state. The first call that sees the run ended finishes it. */
  async look() {
    const state = /** @type {any} */ (await this.ctx.storage.get("state")) || { status: "idle" };
    if (state.status !== "running") return answerOf(state);
    if (this.#launching) return answerOf({ ...state, lines: [STARTING] });
    const fail = (line) => {
      this.#finishing ||= this.finish(state, [line], "1").finally(() => (this.#finishing = null));
      return this.#finishing.then(answerOf);
    };
    // A container that stopped under its run (a crash, an eviction) cannot end it: the run failed.
    if (!this.ctx.container?.running)
      return fail("The run's container stopped before the run ended.");
    let text = "";
    try {
      const res = await new Files(this.container()).readFile(LOG);
      // No log and no start in progress: this object restarted before the run began, and the token,
      // which was in its memory alone, is gone.
      if (!res.ok)
        return fail(
          "The run lost its access to Cloudflare before it began. Connect Cloudflare again.",
        );
      text = await res.text();
    } catch (error) {
      // longer than any run that is well (run.sh bounds each of its steps)
      if (Date.now() - state.startedAt > 45 * 60_000)
        return fail("The run's container did not answer for 45 minutes.");
      text = `(the container isn't answering: ${String(error?.message || error)})`;
    }
    const lines = text.split("\n").filter(Boolean);
    const exit = lines
      .map((l) => /^__EXIT__:(\d+)/.exec(l)?.[1])
      .filter(Boolean)
      .at(-1);
    if (!exit) return answerOf({ ...state, lines: keptLines(lines) });
    this.#finishing ||= this.finish(state, lines, exit).finally(() => (this.#finishing = null));
    return answerOf(await this.#finishing);
  }

  /** Ends a run that has ended in its container: gives up the token, destroys the container, and
   *  stores the final state, which then needs no container. A run that failed has no first owner.
   *  A run whose token still works after the revoke failed, whatever its container said. */
  async finish(state, lines, exit) {
    // nor has a run on a stack whose own config does not name the address (run.sh says so)
    if (exit !== "0" || lines.some((l) => l.startsWith("No first-passkey link:")))
      this.#first = null;
    let forgot;
    const out = lines.filter((l) => !l.startsWith("__EXIT__"));
    out.push("== step forget");
    const ends = `This access ends by itself at ${utc(state.tokenExpiresAt)}.`;
    if (this.#token) {
      const token = this.#token;
      this.#token = null;
      // CF_REVOKE: the installer's config names another endpoint for a pretend Cloudflare; absent, Cloudflare's
      const gave = await giveUp({
        token,
        accountId: state.accountId,
        clientId: this.env.CLIENT_ID,
        clientSecret: this.env.CLIENT_SECRET,
        revokeUrl: this.env.CF_REVOKE,
        api: this.env.CF_API,
      });
      forgot = { revoke: gave.revoke, probe: gave.probe, works: gave.works };
      const said = forgetLinesOf(gave, ends);
      out.push(...said);
      // the Worker's log: the proof of the revoke that needs no person's session
      console.log(JSON.stringify({ message: said[0], zone: state.zone, ...forgot }));
      if (gave.works) this.#first = null;
    } else {
      out.push(ends);
    }
    // The container goes with its run: its disk holds the stack's config and the run's log.
    try {
      await this.ctx.container?.destroy();
    } catch (error) {
      if (this.ctx.container?.running)
        out.push(`The run's container could not be removed: ${String(error?.message || error)}.`);
    }
    const commit = lines.map((l) => /^stack ([0-9a-f]{40})$/.exec(l)?.[1]).find(Boolean) || null;
    // "Update anyway": the commit that this run replaced, which this Cloud does not have
    const replaced = lines.map((l) => /^replaces ([0-9a-f]{40})$/.exec(l)?.[1]).find(Boolean);
    const worked = exit === "0" && !forgot?.works;
    // THE PROOF OF AN UPDATE: which version of each of the stack's Workers Cloudflare ran before
    // the deploy and runs after it (run.sh `versions_now`). A first deploy has no "before".
    const versions = {};
    for (const line of lines) {
      const [, when, worker, version] = /^version (before|after) (\S+) (\S+)$/.exec(line) || [];
      if (when) (versions[worker] ||= { before: null, after: null })[when] = version;
    }
    const final = {
      ...state,
      status: worked ? "succeeded" : "failed",
      endedAt: Date.now(),
      lines: keptLines(out),
      result: worked
        ? {
            issuer: `https://iterate.${state.zone}`,
            commit,
            versions,
            replaced,
          }
        : null,
      // the deploy said whether the stack has the mind's Cloudflare connection, and whether this
      // release made its token; a run that ended before it keeps what the run before it said
      ...connectionAfter(lines, state),
      // the stack keeps its vault key outside Cloudflare: no run from here can deploy it, and
      // "Your deployments" then offers none (run.sh `updatable_from_here`)
      ...(lines.some((l) => l.startsWith(KEY_OUTSIDE)) && { keyOutside: true }),
      forgot,
      // the container's run worked, and the run failed at giving up the access
      ...(exit === "0" && !worked && { failedAt: "forget" }),
      // the erase is done when the run went on to the deploy: a try after it is a first deploy
      ...(state.erase && { erased: lines.includes("== step deploy") }),
    };
    await this.ctx.storage.put("state", final);
    return final;
  }

  /** Only the object named `sign-ins` gets this call (cloudflare-access.js `claimToken`). */
  claim(sessionId) {
    return claimIn(this.ctx.storage, sessionId);
  }

  /** Every record this object keeps, for a page that shows the Cloud holds no token: its storage
   *  keys, each with what its value is, and its alarm. The token is never stored, so never listed. */
  async kept() {
    const records = [...(await this.ctx.storage.list()).keys()].map((key) => ({
      where: "Durable Object storage",
      key: key.startsWith("claim:") ? "claim:" : key,
      what: RECORDS[key.startsWith("claim:") ? "claim:" : key] || "(not described)",
    }));
    if (this.ctx.container?.running)
      records.push({
        where: "Container",
        key: "container",
        what: "The run's container is up. Its disk holds the stack's config and the run's log; the token is in the run's process alone.",
      });
    const alarm = await this.ctx.storage.getAlarm();
    if (alarm)
      records.push({
        where: "Durable Object alarm",
        key: "alarm",
        what: `Wakes this object at ${utc(alarm)} to look at the run.`,
      });
    return { records };
  }

  async alarm() {
    if (await this.ctx.storage.get("install")) return this.installation().alarm();
    const state = await this.look();
    if (state.status === "running") await this.ctx.storage.setAlarm(Date.now() + 10_000);
  }
}

/** A stored state as status() answers it. */
const answerOf = (state) => ({
  status: state.status,
  startedAt: state.startedAt ?? null,
  endedAt: state.endedAt ?? null,
  lines: state.lines || [],
  steps: state.erase ? [STEPS[0], ERASE_STEP, ...STEPS.slice(1)] : STEPS,
  result: state.result ?? null,
  ...(state.erase && { erase: true, erased: !!state.erased }),
  forgot: state.forgot,
  failedAt: state.failedAt,
  ...(state.keyOutside && { keyOutside: true }),
  recorded: state.recorded,
  connection: state.connection,
  connectionEdition: state.connectionEdition,
});