iterate.com / cloud

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

cloud / internal-packages / installer / container / erase.mjsmain at aacbc74

// erase.mjs — THE ERASE OF "ERASE AND REPLACE", in the run's container (run.sh, step `erase`).
// Reads what is on the zone and under the stack's names (takeover.mjs), erases the list the
// person agreed to, and reads again until nothing is left. Exit 0: the zone is empty.
//
// Inputs, from the environment: CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, ITERATE_ZONE,
// ITERATE_ZONE_ID, ITERATE_NAME, and ITERATE_ERASE: the name of the list the person saw.
// `--look` prints the list and erases nothing.
import { CATALOG, eraseAll, inventoryOf, refusalsOf } from "./takeover.mjs";

const env = process.env;
const API = env.CF_API || "https://api.cloudflare.com/client/v4";
const pause = (ms) => new Promise((done) => setTimeout(done, ms));

/** One call of Cloudflare's API. A 429 or a 5xx is asked again, three times at most. A path that
 *  is the address of a data catalog (takeover.mjs `CATALOG`) goes there: never from a run against
 *  a pretend Cloudflare (CF_API), which has no such thing. */
async function cf(method, path, body) {
  const elsewhere = path.startsWith(`${CATALOG}/`);
  if (elsewhere && env.CF_API)
    return { status: 0, success: false, errors: [{ code: 0, message: "no data catalog here" }] };
  let answer;
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const response = await fetch(elsewhere ? path : `${API}${path}`, {
        method,
        headers: {
          authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}`,
          ...(body === undefined ? {} : { "content-type": "application/json" }),
        },
        body: body === undefined ? undefined : JSON.stringify(body),
        signal: AbortSignal.timeout(30_000),
      });
      const text = await response.text();
      let data = {};
      try {
        data = text ? JSON.parse(text) : {};
        // the data catalog says a refusal as { error: { code, message } }
        if (data.error?.message) data = { errors: [data.error] };
      } catch {
        data = { errors: [{ code: response.status, message: text.slice(0, 200) }] };
      }
      answer = { ...data, status: response.status, success: data.success ?? response.ok };
      if (response.status !== 429 && response.status < 500) return answer;
    } catch (error) {
      answer = { status: 0, success: false, errors: [{ code: 0, message: String(error) }] };
    }
    if (attempt < 3) await pause(attempt * 2000);
  }
  return answer;
}

const given = {
  cf,
  accountId: env.CLOUDFLARE_ACCOUNT_ID,
  zoneId: env.ITERATE_ZONE_ID,
  zone: env.ITERATE_ZONE,
  name: env.ITERATE_NAME,
};
if (!env.CLOUDFLARE_API_TOKEN || !given.accountId || !given.zoneId || !given.zone || !given.name) {
  console.log("Stopped: the erase did not get its inputs.");
  process.exit(1);
}

if (process.argv.includes("--look")) {
  const found = await inventoryOf(given);
  console.log(JSON.stringify({ ...found, refusals: refusalsOf(found) }, null, 1));
  process.exit(0);
}

if (!env.ITERATE_ERASE) {
  console.log("Stopped: nobody agreed to a list of what is erased.");
  process.exit(1);
}
const done = await eraseAll({
  ...given,
  agreed: env.ITERATE_ERASE,
  say: (line) => console.log(line),
});
if (!done.ok) {
  console.log(`Stopped: ${done.why}`);
  process.exit(1);
}