iterate.com / cloud

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

cloud / internal-packages / installer / scripts / deploy-prd.mjsmain at aacbc74

// deploy-prd.mjs — HOW iterate-cloud-prd GOES TO PRODUCTION (`pnpm run deploy:prd`).
//
// This Worker carries every provider's webhook to every mind, so a deploy of it reaches all of
// them at once (README "Production"). So this script:
//   1. REFUSES a tree that is not a clean commit of origin/main: production runs merged code alone.
//   2. SAYS WHAT GOES LIVE: the commits between the version that is live and this one.
//   3. DEPLOYS THE COMMIT THAT WAS APPROVED OVER THE VERSION THAT WAS APPROVED, AND NOTHING ELSE
//      (`deploy`, `guardOf`). `--plan` names both; whoever approves the deploy passes them back
//      as `--commit` and `--expect-live`. The run takes the lock file `--lock` before its first
//      read and holds it to its end. It reads the tree and the live version twice: before the
//      build, and again after the build, right before the upload. It uploads nothing when the
//      tree is not at that commit, when the Worker does not serve that one version at 100%, when
//      the live commit is not known to lie behind this one, and when a flag is missing.
//   4. Packs the stack for the Deployer's image, builds, and uploads with the commit in the
//      version's message (`main <commit>`), which the next deploy reads in step 2.
//   5. READS THE DEPLOYER'S IMAGE (`imageOf`: the application, its rollouts, and the registry's
//      digest under each upload's tag). One `wrangler deploy` makes two changes, one after
//      the other: the Worker's new version, then the push of the Deployer's image and the rollout
//      of the container application to it. When the second fails (a registry timeout), the Worker
//      serves the new commit and the Deployer runs the image of an older one: A PARTIAL ROLLOUT.
//      The run ends with exit 3 and says so. A later run for the same commit refuses (exit 2):
//      the Worker's version alone is not "already live". `--repair-image` is the way out (below).
//   6. READS THE WORKER'S LOG SINCE THE UPLOAD for some minutes. An error or a thrown invocation
//      ends the run with exit 1 and the line that goes back to the approved version.
//
//   doppler run --project _shared --config prd --only-secrets CLOUDFLARE_API_TOKEN -- pnpm run deploy:prd --plan
//   … pnpm run deploy:prd --commit <commit> --expect-live <version id> --lock ~/.cache/beelink-heavy-check.lock
//   … node scripts/deploy-prd.mjs --check --from <ISO time>   # step 6 alone, read-only: the 3 minutes from then
//   … pnpm run deploy:prd --commit <commit> --expect-live <version id> --lock <file> --repair-image
//
// `--repair-image` REPAIRS A PARTIAL ROLLOUT, AND NOTHING ELSE: the same guarded deploy, of the
// commit that the Worker serves already, so that the image is pushed and rolled out. It needs
// its own plan and its own approval (`--plan` prints the line when the rollout is partial). It
// uploads the Worker's code once more, as a new version of the same commit, because one upload
// path is tested and a rollout by hand is not. It refuses when the live commit is not this
// commit, and it does nothing when the image is of this commit already.
//
// The script takes the lock itself (`flock`): do not wrap the deploy in `flock` on the same file,
// or it waits for itself.
//
// THE EXIT STATUS SAYS WHETHER PRODUCTION MAY HAVE CHANGED:
//   0  live and verified by the log; or this commit was live already, the Deployer's image
//      too; or a plan
//   1  uploaded and live, and the log shows a fault or no invocation
//   2  NOTHING WAS UPLOADED: a refusal (a partial rollout that no `--repair-image` names is
//      one), or a step before the upload failed
//   3  THE UPLOAD WAS ATTEMPTED AND THE LIVE STATE IS NOT VERIFIED: the upload failed part-way,
//      a read after it failed (of the deployments, of the image or of the log), the deployments
//      are not what this upload should leave, or the Deployer's image is not of this commit. The
//      last lines say what was read after the failure: nothing live changed, a PARTIAL ROLLOUT,
//      or not known. Read the deployments before any new plan.
//
// WHAT THIS DOES NOT STOP. Cloudflare has no upload that names the version it replaces. A
// deployment by another hand in the seconds between the last read and the upload is replaced by
// this upload all the same. The read after the upload sees it only after the fact (the deployment
// right before the new one is then not the approved version: exit 3), and only while that
// deployment is still the one right before. The way-back line names the approved version, which
// is the version that this upload replaced only when no such deployment landed. And nothing stops
// a person who calls `wrangler deploy` by hand: no setting at Cloudflare does.
import { execFileSync, spawnSync } from "node:child_process";
import { closeSync, openSync, readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

const here = fileURLToPath(new URL("..", import.meta.url));
/** What the Worker's own code is built from. The Deployer's image holds the whole repository
 *  (`container/pack-stack.sh`), so every other commit of main changes that image alone. */
const OWN_PATHS = [
  "internal-packages/installer",
  "internal-packages/cloud-clients",
  "internal-packages/cloud-ai",
];
/** How long the log is read after the upload: an object that cannot run its alarm throws within
 *  the first minute. */
const WATCH_MS = 3 * 60_000;

const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();

/** THE COMMIT THIS TREE MAY RELEASE: its HEAD, when the tree is clean and HEAD is a commit of
 *  origin/main as it is now. It throws, with the reason, for any other tree. */
export function releaseOf(cwd) {
  git(cwd, "fetch", "--quiet", "origin", "main");
  const head = git(cwd, "rev-parse", "HEAD");
  const changed = git(cwd, "status", "--porcelain");
  if (changed) throw new Error(`REFUSED: the tree is not clean:\n${changed}`);
  const merged = spawnSync("git", ["merge-base", "--is-ancestor", head, "origin/main"], { cwd });
  if (merged.status !== 0)
    throw new Error(
      `REFUSED: ${head} is not a commit of origin/main. Production runs merged code alone: merge first, then deploy main.`,
    );
  return head;
}

/** THE VERSION THAT IS LIVE, AND THE COMMIT IT WAS BUILT FROM. `deployments` are newest first.
 *  The commit is the one in the message (`main <commit>`) of the upload that made the live
 *  version, found by the version's id: never the newest message that names a commit. After a
 *  rollback from B to A the newest such message is B's, and the next deploy would then leave out
 *  what lies between A and B, which goes live again. A change of a secret makes a new version of
 *  the same code with no message, so from such a deployment the search goes on at the one before.
 *  `commit` is null when the live code's upload names none.
 *
 *  IT THROWS WHEN THE WORKER DOES NOT SERVE ONE VERSION AT 100%. A deployment can split its
 *  traffic between versions, and the first of them is then not "the live version": a deploy that
 *  compared with it alone would call a half-released commit live. The same holds for each
 *  deployment that the search for the code passes. */
export function liveOf(deployments) {
  if (deployments.length === 0)
    throw new Error("REFUSED: the Worker has no deployment, so no version is live.");
  const versionOf = (deployment) => {
    const versions = deployment.versions || [];
    if (versions.length !== 1 || versions[0].percentage !== 100 || !versions[0].version_id)
      throw new Error(
        `REFUSED: the Worker does not serve one version at 100%. Deployment ${deployment.id} serves ${
          versions.map((each) => `${each.version_id} at ${each.percentage}%`).join(", ") ||
          "no version"
        }. Nothing is uploaded over a split: end the split first.`,
      );
    return versions[0].version_id;
  };
  const commitOf = (deployment) =>
    /^main ([0-9a-f]{40})$/.exec(deployment.annotations?.["workers/message"] || "")?.[1];
  const version = versionOf(deployments[0]);
  let at = 0;
  while (deployments[at]?.annotations?.["workers/triggered_by"] === "secret") {
    versionOf(deployments[at]);
    at += 1;
  }
  if (!deployments[at]) return { version, commit: null };
  const code = versionOf(deployments[at]);
  // an older deployment that split its traffic is not the upload of one version: it is passed over
  const upload = deployments.find(
    (each) => each.versions?.length === 1 && each.versions[0].version_id === code && commitOf(each),
  );
  return { version, commit: (upload && commitOf(upload)) || null };
}

/** WHERE THE LIVE COMMIT LIES FROM `head`: "same", "behind" (a deploy releases what lies
 *  between), or why that is not known: "not-named" (no upload of this script made the live code),
 *  "not-in-clone", "not-behind" (the deploy would go back, or the two are on different lines). */
function ancestryOf(cwd, live, head) {
  if (!live) return "not-named";
  if (spawnSync("git", ["cat-file", "-e", `${live}^{commit}`], { cwd }).status !== 0)
    return "not-in-clone";
  if (live === head) return "same";
  if (spawnSync("git", ["merge-base", "--is-ancestor", live, head], { cwd }).status !== 0)
    return "not-behind";
  return "behind";
}

/** THE GUARD OF AN UPLOAD: `deployments` as read now, `head` to release, `expected` the id of the
 *  live version that the deploy was approved over. It answers "same" (`head` is live already:
 *  there is nothing to upload) or "behind" (the upload may go on). It throws, with the reason,
 *  for everything else: a split (`liveOf`), a live version that is not the approved one, and a
 *  live commit that is not known to lie behind `head`. */
export function guardOf(cwd, deployments, head, expected) {
  if (!expected)
    throw new Error(
      "REFUSED: no approved live version. Read it with --plan, and pass it as --expect-live <version id>.",
    );
  const live = liveOf(deployments);
  if (live.version !== expected)
    throw new Error(
      `REFUSED: the live version is ${live.version}, and this deploy was approved over ${expected}. Somebody deployed or changed a secret since the plan: plan again.`,
    );
  const ancestry = ancestryOf(cwd, live.commit, head);
  switch (ancestry) {
    case "same":
    case "behind":
      return ancestry;
    default:
      throw new Error(
        `REFUSED: it is not known what this deploy releases.\n${releasedBetween(cwd, live.commit, head).join("\n")}`,
      );
  }
}

/** The uploads of this script among `deployments`: one version, and a message that names a commit. */
const uploadsOf = (deployments) =>
  deployments.filter(
    (each) =>
      each.versions?.length === 1 &&
      each.versions[0].version_id &&
      /^main [0-9a-f]{40}$/.test(each.annotations?.["workers/message"] || ""),
  );

/** THE DEPLOYER'S IMAGE, AND THE COMMIT IT WAS BUILT FROM. `read` is what `api.image` answers:
 *  the container application, its rollouts (newest first), and `digests`: for each upload of
 *  this script among `deployments`, by its version's id, the digest that the registry holds
 *  under that version's tag, or null when the registry has no such tag.
 *  THE TIE IS WRANGLER'S OWN TAG. The application names its image by digest alone. `wrangler
 *  deploy` uploads the Worker's version first and then pushes the image under the tag
 *  `<the first part of that version's id>` (`getContainerImageTag`). So the image is of a commit
 *  when its digest is the one under the tag of an upload of that commit. No time and no order of
 *  events stands in for that: a rollout that an overlapping deploy started late proves nothing.
 *  A deploy of a commit whose image the registry holds already pushes no new tag (wrangler:
 *  "Image already exists remotely"), and the digest is then under the tag of an earlier upload
 *  of that same commit: every upload of the commit counts.
 *  `commit` is null when it is not known, and `why` then says why: no application, a rollout
 *  that has not ended, or a digest that no listed upload's tag names. An image that is not known
 *  to be of a commit is never called in step with it. */
export function imageOf(deployments, read) {
  const { application, rollouts = [], digests = {} } = read || {};
  if (!application)
    return { image: null, commit: null, why: "the account has no such container application" };
  const image = application.configuration?.image || null;
  const known = { image, version: application.version };
  const rollout = rollouts[0];
  if (application.active_rollout_id || (rollout && rollout.status !== "completed"))
    return {
      ...known,
      commit: null,
      why: `a rollout of the application has not ended (${rollout ? `${rollout.id}, status ${rollout.status}` : application.active_rollout_id})`,
    };
  const digest = /@(sha256:[0-9a-f]{64})$/.exec(image || "")?.[1];
  if (!digest) return { ...known, commit: null, why: "the application's image names no digest" };
  const uploads = uploadsOf(deployments);
  const commits = new Set(
    uploads
      .filter((each) => digests[each.versions[0].version_id] === digest)
      .map((each) => each.annotations["workers/message"].slice(5)),
  );
  if (commits.size !== 1)
    return {
      ...known,
      commit: null,
      why:
        commits.size === 0
          ? `the registry holds its digest under the tag of none of the ${uploads.length} uploads of this script that Cloudflare lists`
          : "the registry holds its digest under the tags of uploads of different commits",
    };
  return { ...known, commit: [...commits][0] };
}

/** One line for a person: the Deployer's image and the commit that it is of. */
const imageLine = (image) =>
  `Deployer's image: application version ${image.version ?? "none"}, ${
    image.commit ? `commit ${image.commit}` : `commit NOT KNOWN (${image.why})`
  }`;

/** What a Worker of `commit` (as `version`) with an image that is not known to be of it says.
 *  AN IMAGE OF ANOTHER COMMIT IS A PARTIAL ROLLOUT, and the last line is the repair's own flags,
 *  which a person approves like any deploy. AN IMAGE WHOSE COMMIT IS NOT KNOWN NAMES NO REPAIR:
 *  the repair is verified by the same read, and a read that does not know the image before the
 *  upload may not know it after it either (wrangler pushes no new tag for an image that the
 *  registry holds already, and Cloudflare lists ten deployments). */
const partialLines = (commit, version, image, lock = "<file>") =>
  image.commit
    ? [
        `PARTIAL ROLLOUT: the Worker serves version ${version} of commit ${commit}, and the Deployer's image is of commit ${image.commit}.`,
        "The Deployer runs, with that image: an install or an update that it starts uses that image's stack.",
        `To repair, on a GO for exactly these flags: --commit ${commit} --expect-live ${version} --lock ${lock} --repair-image`,
      ]
    : [
        `THE DEPLOYER'S IMAGE IS NOT KNOWN TO BE OF THIS COMMIT: the Worker serves version ${version} of commit ${commit}. NOT KNOWN: which commit the image is of (${image.why}).`,
        "No repair is named. When a rollout has not ended, plan again after it. Else a person reads the application and the registry, and decides.",
      ];

/** What a deploy of `head` over `live` releases, as lines for a person. */
export function releasedBetween(cwd, live, head) {
  switch (ancestryOf(cwd, live, head)) {
    case "not-named":
      return [
        "The live version names no commit (this script did not upload it).",
        "NOT KNOWN: which commits this deploy releases. Read the pull requests merged since the last deploy.",
      ];
    case "not-in-clone":
      return [
        `The live version names ${live}, which this clone does not have. NOT KNOWN: what goes live.`,
      ];
    case "not-behind":
      return [`THIS DEPLOY GOES BACK: the live commit ${live} is not behind ${head}.`];
    case "same":
      return [`NOTHING TO RELEASE: the live version was built from this commit, ${head}.`];
  }
  const top = git(cwd, "rev-parse", "--show-toplevel");
  const own = git(top, "log", "--format=%h %s", `${live}..${head}`, "--", ...OWN_PATHS);
  const all = Number(git(top, "rev-list", "--count", `${live}..${head}`));
  const lines = own ? own.split("\n") : [];
  return [
    `This deploy releases ${lines.length} commits to the Worker's own code (${all} commits of main in all, which the Deployer's image holds):`,
    ...lines.map((line) => `  ${line}`),
  ];
}

/** wrangler.jsonc as JSON: its comments are whole lines, and its lists end with a comma. */
function prdConfig() {
  const config = JSON.parse(
    readFileSync(new URL("../wrangler.jsonc", import.meta.url), "utf8")
      .replace(/^\s*\/\/.*$/gm, "")
      .replace(/,(\s*[}\]])/g, "$1"),
  );
  return {
    account: config.env.prd.account_id,
    worker: `${config.name}-prd`,
    // wrangler's name for the container application of a class: <name>-<class>-<environment>
    container: `${config.name}-${config.env.prd.containers[0].class_name.toLowerCase()}-prd`,
  };
}

/** Cloudflare's registry of container images, and the kinds of manifest that a tag can name. */
const REGISTRY = "registry.cloudflare.com";
const MANIFESTS = [
  "application/vnd.oci.image.manifest.v1+json",
  "application/vnd.docker.distribution.manifest.v2+json",
  "application/vnd.oci.image.index.v1+json",
  "application/vnd.docker.distribution.manifest.list.v2+json",
].join(", ");

/** Cloudflare's API for the production account, with the token of the environment. */
function cloudflare() {
  const { account, worker, container } = prdConfig();
  const token = process.env.CLOUDFLARE_API_TOKEN;
  if (!token)
    throw new Error(
      "CLOUDFLARE_API_TOKEN is not set: run under doppler (see the top of this file)",
    );
  const call = async (path, body) => {
    const answer = await fetch(`https://api.cloudflare.com/client/v4/accounts/${account}${path}`, {
      method: body ? "POST" : "GET",
      headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
      body: body && JSON.stringify(body),
    });
    const read = await answer.json().catch(() => ({}));
    if (!read.success)
      throw new Error(
        `Cloudflare ${path}: ${answer.status} ${JSON.stringify(read.errors || read).slice(0, 300)}`,
      );
    return read.result;
  };
  /** The registry's sign-in, kept for 10 of its 15 minutes: `[basic, made]`. */
  let pull;
  /** The digests that the registry answered: a tag that holds an image keeps it. */
  const seen = new Map();
  /** The digest under `tag` of the Deployer's repository, or null when there is no such tag. */
  const tagged = async (tag) => {
    if (seen.has(tag)) return seen.get(tag);
    if (!pull || Date.now() - pull[1] > 10 * 60_000) {
      const made = await call(`/containers/registries/${REGISTRY}/credentials`, {
        expiration_minutes: 15,
        permissions: ["pull"],
      });
      pull = [Buffer.from(`v1:${made.password}`).toString("base64"), Date.now()];
    }
    const answer = await fetch(`https://${REGISTRY}/v2/${account}/${container}/manifests/${tag}`, {
      method: "HEAD",
      headers: { authorization: `Basic ${pull[0]}`, accept: MANIFESTS },
    });
    if (answer.status === 404) return null;
    const digest = answer.headers.get("docker-content-digest");
    if (!answer.ok || !digest)
      throw new Error(`${REGISTRY} manifests/${tag}: ${answer.status}, no digest`);
    seen.set(tag, digest);
    return digest;
  };
  return {
    worker,
    deployments: async () =>
      (await call(`/workers/scripts/${worker}/deployments`)).deployments || [],
    /** The Deployer's container application, its rollouts (newest first), and the registry's
     *  digest under the tag of each upload of this script among `deployments` (`imageOf`). It
     *  changes nothing at Cloudflare. For the registry it asks Cloudflare for a credential that
     *  may pull alone and that ends after 15 minutes, as wrangler does for its own reads. */
    image: async (deployments) => {
      const application = (await call("/containers/applications")).find(
        (each) => each.name === container,
      );
      if (!application) return { application: null, rollouts: [], digests: {} };
      const rollouts = await call(`/containers/applications/${application.id}/rollouts`);
      const digests = {};
      for (const each of uploadsOf(deployments)) {
        const version = each.versions[0].version_id;
        digests[version] = await tagged(version.split("-")[0]);
      }
      return {
        application,
        rollouts: [...rollouts].sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)),
        digests,
      };
    },
    /** A count of the Worker's log rows that pass `filters`, by `groups`: [[group…, count]]. */
    count: async (from, to, filters, groups) => {
      const result = await call("/workers/observability/telemetry/query", {
        queryId: "deploy-prd",
        view: "calculations",
        dry: true,
        limit: 20,
        timeframe: { from, to },
        parameters: {
          datasets: ["cloudflare-workers"],
          limit: 20,
          filters: [
            { key: "$metadata.service", operation: "eq", type: "string", value: worker },
            ...filters,
          ],
          calculations: [{ operator: "count" }],
          groupBys: groups.map((value) => ({ type: "string", value })),
        },
      });
      return (result.calculations?.[0]?.aggregates || []).map((row) => [
        ...(row.groups || []).map((group) => String(group.value)),
        row.count,
      ]);
    },
  };
}

const leaf = (key, operation, value) => ({ key, operation, type: "string", value });
/** A line that the code logged, and not the summary row of an invocation: a thrown invocation's
 *  summary is an error row too, and it is counted once, as thrown. */
const LINE = {
  kind: "group",
  filterCombination: "or",
  filters: [
    { key: "$metadata.type", operation: "is_null", type: "string" },
    leaf("$metadata.type", "neq", "cf-worker-event"),
  ],
};

/** WHAT THE WORKER'S LOG SAYS from `from` to `to`: how many invocations it had, and its faults,
 *  each a line for a person. A fault is an error line or an invocation that threw. EVERY VERSION
 *  IS READ, not the new one alone: the log can name the version before for an object that
 *  throws in the first minute, and a change of a secret makes a new version of the same code.
 *  Any error counts: the Worker logs none when it works. The log is the Worker's own word: this
 *  reads no delivery on a mind's log. */
export async function faultsOf(api, from, to) {
  const [invocations, errors, thrown] = await Promise.all([
    api.count(from, to, [leaf("$metadata.type", "eq", "cf-worker-event")], []),
    api.count(from, to, [leaf("$metadata.level", "eq", "error"), LINE], ["$metadata.message"]),
    api.count(
      from,
      to,
      [leaf("$workers.outcome", "eq", "exception")],
      ["$workers.entrypoint", "$workers.eventType"],
    ),
  ]);
  return {
    invocations: invocations.reduce((sum, row) => sum + Number(row.at(-1)), 0),
    faults: [
      ...errors.map(([message, count]) => `${count} × error: ${message.slice(0, 160)}`),
      ...thrown.map(([entrypoint, event, count]) => `${count} × threw: ${entrypoint} ${event}`),
    ],
  };
}

function run(command, args, env = process.env) {
  console.log(`\n$ ${command} ${args.join(" ")}`);
  const done = spawnSync(command, args, { cwd: here, env, stdio: "inherit" });
  if (done.status !== 0) throw new Error(`${command} ${args[0]} ended with exit ${done.status}`);
}

/** Step 5: reads the log from `from` until a fault shows or `until` has passed. `before` is the
 *  approved version, which was live right before the upload. */
async function watch(api, from, until, before) {
  for (;;) {
    const now = Date.now();
    const { invocations, faults } = await faultsOf(api, from, Math.min(now, until));
    console.log(
      `${new Date(now).toISOString()} since ${new Date(from).toISOString()}: ${invocations} invocations, ${faults.length} kinds of fault`,
    );
    if (faults.length > 0) {
      console.error(`\nFAULT since the upload:\n${faults.map((line) => `  ${line}`).join("\n")}`);
      if (before)
        console.error(
          `\nTo go back to the approved version, which was live before this upload:\n  pnpm exec wrangler rollback ${before} --env prd --message "faults after the deploy"`,
        );
      return false;
    }
    if (now >= until) {
      if (invocations > 0) return true;
      console.error("\nNOT VERIFIED: the log shows no invocation since the upload.");
      return false;
    }
    await new Promise((resolve) => setTimeout(resolve, 30_000));
  }
}

/** What `flock` exits with when it did not get the lock. */
const LOCK_NOT_TAKEN = 75;
/** How long the deploy waits for the lock: a whole-repo check of another agent ends within it. */
const LOCK_WAIT_SECONDS = 15 * 60;

/** TAKES THE LOCK FILE `lock` FOR THIS PROCESS, and answers the open file that holds it. The lock
 *  is this process's own: `flock` takes it on the file that this process opened, so it is held
 *  until this process closes that file or ends, and no other job's hold of the lock can pass for
 *  it. It throws when the lock stays taken for `waitSeconds`, and when `flock` cannot run. */
export function takeLock(lock, waitSeconds = LOCK_WAIT_SECONDS) {
  const file = openSync(lock, "a");
  // `flock 3`: the child's file 3 is the one this process opened, and the lock stays with it
  const done = spawnSync(
    "flock",
    ["--timeout", String(waitSeconds), "--conflict-exit-code", String(LOCK_NOT_TAKEN), "3"],
    { stdio: ["ignore", "inherit", "inherit", file] },
  );
  if (done.status === 0) return file;
  closeSync(file);
  if (done.status === LOCK_NOT_TAKEN)
    throw new Error(
      `REFUSED: ${lock} stayed taken for ${waitSeconds} seconds. Nothing was built and nothing was uploaded.`,
    );
  throw new Error(
    `REFUSED: flock did not take ${lock}: ${done.error?.message || `exit ${done.status}`}. Nothing was built and nothing was uploaded.`,
  );
}

/** An error after the upload began: production may have changed, and this run did not verify it. */
class UploadNotVerified extends Error {}

/** ONE GUARDED DEPLOY of the tree at `cwd`: of the commit `commit`, over the live version
 *  `expected`, both as they were approved. `build` and `upload` are the two steps that take the
 *  commit; `api.deployments` reads the Worker's deployments; `verify(from, before)` reads the
 *  Worker's log since the upload and answers whether it shows no fault.
 *  THE ORDER IS THE GUARD: the tree and the live version are read before the build, so that a
 *  refusal costs no build, AND AGAIN AFTER THE BUILD, right before the upload: a build takes
 *  minutes, in which another deploy can land and the tree can move.
 *  `api.image` reads the Deployer's application and its rollouts. A COMMIT IS LIVE ONLY WHEN THE
 *  WORKER AND THE DEPLOYER'S IMAGE ARE BOTH OF IT (`imageOf`): a Worker of this commit with an
 *  image of another is a partial rollout, and it is refused unless `repair` is set. `repair`
 *  runs the same deploy for the commit that is live already, and for no other. After the upload
 *  the image is read up to `settle.tries` times, `settle.pauseMs` apart, until its rollout ended,
 *  and then the live version once more. A repair needs an image of a KNOWN other commit.
 *  It answers null when the commit was live already, image and all, else the new version and
 *  `well`: what the log check answered. An error from the upload on, the image's and the log
 *  check's too, is an `UploadNotVerified`; every error before it means that nothing was uploaded. */
export async function deploy({
  api,
  cwd,
  commit,
  expected,
  build,
  upload,
  verify,
  repair = false,
  lock,
  settle = { tries: 30, pauseMs: 10_000 },
}) {
  if (!/^[0-9a-f]{40}$/.test(commit || ""))
    throw new Error(
      "REFUSED: no approved commit. --plan names it: pass it as --commit <the 40 characters>.",
    );
  const treeIsApproved = () => {
    const head = releaseOf(cwd);
    if (head !== commit)
      throw new Error(
        `REFUSED: the tree is at ${head}, and the approved commit is ${commit}. Nothing was uploaded.`,
      );
  };
  treeIsApproved();
  const deployments = await api.deployments();
  const ancestry = guardOf(cwd, deployments, commit, expected);
  const live = liveOf(deployments);
  console.log(`Deploying from ${git(cwd, "log", "-1", "--format=%H %s")}`);
  console.log(`Live now: version ${live.version}, commit ${live.commit}`);
  console.log(releasedBetween(cwd, live.commit, commit).join("\n"));
  // read before the build: a token that cannot read the image could not verify the upload either
  const image = imageOf(deployments, await api.image(deployments));
  console.log(imageLine(image));
  if (ancestry === "same") {
    if (image.commit === commit) return null;
    // without the flag, and with it for an image whose commit is not known: no upload
    if (!repair || !image.commit)
      throw new Error(
        `REFUSED: ${partialLines(commit, live.version, image, lock).join("\n")}\nNothing was built and nothing was uploaded.`,
      );
    console.log(
      "REPAIR: this commit is uploaded once more, so that its image is pushed and rolled out.",
    );
  } else if (repair)
    throw new Error(
      `REFUSED: --repair-image is for the commit that the Worker serves already. The live commit is ${live.commit}, not ${commit}: this is a deploy, so plan it as one. Nothing was uploaded.`,
    );

  build(commit);
  treeIsApproved();
  const again = await api.deployments();
  guardOf(cwd, again, commit, expected);
  if (repair) {
    // the image is read again as the live version is: a build takes minutes, in which a
    // rollout can start or end. The repair uploads over an image of a known other commit alone.
    const now = imageOf(again, await api.image(again));
    if (now.commit === commit) {
      console.log(
        "The Deployer's image came to this commit during the build: nothing is uploaded.",
      );
      return null;
    }
    if (!now.commit)
      throw new Error(
        `REFUSED: ${partialLines(commit, live.version, now, lock).join("\n")}\nThe image changed during the build. Nothing was uploaded.`,
      );
  }
  const uploaded = Date.now();
  let after;
  try {
    try {
      upload(commit);
    } catch (error) {
      // THE UPLOAD STEP FAILED PART-WAY. Which part went live is read here, for the person who
      // decides what comes next: the exit status stays 3, and nothing is repaired or retried.
      throw new Error(
        `${error instanceof Error ? error.message : error}\n${await stateAfter(api, commit, expected, lock)}`,
      );
    }
    after = await api.deployments();
    const now = liveOf(after);
    if (now.version === expected)
      throw new Error("the upload ended well, and the live version did not change.");
    if (now.commit !== commit)
      throw new Error(
        `the live version ${now.version} names ${now.commit || "no commit"}, not ${commit}: another deployment landed after this upload.`,
      );
    // THE DEPLOYMENT RIGHT BEFORE THE NEW ONE IS WHAT THE UPLOAD REPLACED. Cloudflare has no
    // upload that names the version it replaces, so a deployment by another hand between the
    // last read and the upload is not stopped: it is seen here, after the fact.
    const replaced = liveOf(after.slice(1)).version;
    if (replaced !== expected)
      throw new Error(
        `this upload replaced version ${replaced}, not the approved ${expected}: another deployment landed between the last read and the upload. A way back goes to ${replaced} or to ${expected}: a person decides which.`,
      );
    let rolled = imageOf(after, await api.image(after));
    for (let tries = 1; rolled.commit !== commit && tries < settle.tries; tries += 1) {
      await new Promise((resolve) => setTimeout(resolve, settle.pauseMs));
      rolled = imageOf(after, await api.image(after));
    }
    console.log(imageLine(rolled));
    if (rolled.commit !== commit)
      throw new Error(partialLines(commit, now.version, rolled, lock).join("\n"));
    // THE IMAGE WAS READ AGAINST THE DEPLOYMENTS OF BEFORE THE WAIT. A deployment by another
    // hand during the wait changes what serves: the Worker is read once more, after the image.
    const served = liveOf(await api.deployments());
    if (served.version !== now.version)
      throw new Error(
        `the image came to this commit, and the live version is now ${served.version} of commit ${served.commit || "not named"}, not this upload's ${now.version}: another deployment landed while the image rolled out.`,
      );
    console.log(`\nLive: version ${now.version}. Reading the log since the upload.`);
    return { version: now.version, well: await verify(uploaded, expected) };
  } catch (error) {
    throw new UploadNotVerified(
      `UPLOAD ATTEMPTED, LIVE STATE NOT VERIFIED: ${error instanceof Error ? error.message : error}\nProduction may have changed. Read the deployments before any new plan.`,
    );
  }
}

/** WHAT IS LIVE AFTER AN UPLOAD STEP THAT FAILED, as lines for a person. It reads, and it
 *  changes nothing. A read that fails is said too: the state is then not known. */
async function stateAfter(api, commit, expected, lock) {
  try {
    const deployments = await api.deployments();
    const now = liveOf(deployments);
    const image = imageOf(deployments, await api.image(deployments));
    if (now.version === expected)
      return `READ AFTER THE FAILURE: the Worker still serves the approved version ${expected}. No new version went live. ${imageLine(image)}`;
    if (now.commit !== commit)
      return `READ AFTER THE FAILURE: the live version is ${now.version} of commit ${now.commit || "not named"}: neither the approved version nor this upload's. ${imageLine(image)}`;
    if (image.commit === commit)
      return `READ AFTER THE FAILURE: the Worker serves version ${now.version} of this commit, and the Deployer's image is of it too. The log was not read: --check --from <the upload's time>.`;
    return `READ AFTER THE FAILURE: ${partialLines(commit, now.version, image, lock).join("\n")}`;
  } catch (error) {
    return `READ AFTER THE FAILURE: NOT KNOWN, the read failed: ${error instanceof Error ? error.message : error}`;
  }
}

/** Answers the exit status: 0 for a deploy that the log verified, a commit that was live
 *  already, or a plan; 1 for a deploy or a check that the log did not verify. */
async function main() {
  const { values } = parseArgs({
    options: {
      check: { type: "boolean" },
      from: { type: "string" },
      plan: { type: "boolean" },
      commit: { type: "string" },
      "expect-live": { type: "string" },
      lock: { type: "string" },
      "repair-image": { type: "boolean" },
    },
  });
  if (values.check) {
    const from = Date.parse(values.from || "");
    if (!Number.isFinite(from)) throw new Error("--check needs --from <ISO time>");
    return verdict(await watch(cloudflare(), from, from + WATCH_MS, null));
  }
  if (values.plan) {
    const api = cloudflare();
    const head = releaseOf(here);
    const deployments = await api.deployments();
    const live = liveOf(deployments);
    const image = imageOf(deployments, await api.image(deployments));
    console.log(`A deploy of ${api.worker} from ${git(here, "log", "-1", "--format=%H %s")}`);
    console.log(`Live now: version ${live.version}, commit ${live.commit || "not named"}`);
    console.log(imageLine(image));
    console.log(releasedBetween(here, live.commit, head).join("\n"));
    if (live.commit === head && image.commit !== head) {
      console.log(`\n${partialLines(head, live.version, image).join("\n")}`);
      return 0;
    }
    if (live.commit && image.commit !== live.commit)
      console.log(
        "The Deployer's image is not of the live commit. A deploy of this commit pushes and rolls out its own image.",
      );
    const behind = Number(git(here, "rev-list", "--count", `${head}..origin/main`));
    if (behind > 0) console.log(`origin/main is ${behind} commits ahead of this commit.`);
    console.log(
      `\nTo deploy this commit over this version, and nothing else: --commit ${head} --expect-live ${live.version}`,
    );
    return 0;
  }

  const { commit, lock } = values;
  const expected = values["expect-live"];
  if (!commit)
    throw new Error(
      "REFUSED: no approved commit. --plan names it: pass it as --commit <the 40 characters>.",
    );
  if (!expected)
    throw new Error(
      "REFUSED: no approved live version. Read it with --plan, and pass it as --expect-live <version id>.",
    );
  if (!lock)
    throw new Error(
      "REFUSED: no lock. Pass --lock <file>, the file that every heavy job on this machine takes (on beelink ~/.cache/beelink-heavy-check.lock).",
    );
  // held to the end of this process: the file is never closed
  takeLock(lock);

  const api = cloudflare();
  // the config names the account: an account id from the shell would send the upload elsewhere
  const { CLOUDFLARE_ACCOUNT_ID: _account, ...env } = process.env;
  const done = await deploy({
    api,
    cwd: here,
    commit,
    expected,
    build: (head) => {
      // the Deployer's image copies container/stack/: the stack's source at this same commit
      run("./container/pack-stack.sh", [head], env);
      run("pnpm", ["exec", "vite", "build"], { ...env, CLOUDFLARE_ENV: "prd" });
    },
    upload: (head) =>
      run(
        "pnpm",
        ["exec", "wrangler", "deploy", "--tag", head.slice(0, 12), "--message", `main ${head}`],
        env,
      ),
    verify: (from, before) => watch(api, from, Date.now() + WATCH_MS, before),
    repair: Boolean(values["repair-image"]),
    lock,
  });
  if (!done) {
    console.log(
      "\nNOTHING TO DEPLOY: this commit is live at 100%, and the Deployer's image is of it. Nothing was uploaded.",
    );
    return 0;
  }
  return verdict(done.well);
}

function verdict(well) {
  console.log(
    well ? "\nThe log shows no fault since the upload." : "\nThe deploy is NOT verified.",
  );
  return well ? 0 : 1;
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  try {
    process.exit(await main());
  } catch (error) {
    console.error(String(error instanceof Error ? error.message : error));
    process.exit(error instanceof UploadNotVerified ? 3 : 2);
  }
}