cloud / internal-packages / installer / src / deploy-steps.tsmain at aacbc74
// deploy-steps.ts — WHAT A DEPLOY RUN'S LOG SAYS ABOUT ITS STEPS, for the page (Wizard.tsx) and for
// the activity log (api.ts). A log line `== step <id>` starts a step. Every run ends with the step
// "forget", in which it gives up its access to Cloudflare, also after a failure. So the step that
// failed is the last one the run reached BEFORE "forget". "forget" itself fails in one way: the
// access still works after it, and then the run says so (`failedAt`).
import type { DeployState } from "./api.ts";
type Run = Pick<DeployState, "status" | "lines" | "failedAt">;
export type RunStep = { id: string; lines: string[] };
export type Phase = "done" | "now" | "failed" | "todo";
const FORGET = "forget";
/** The run's lines by step, in order. Lines before the first step are the step "": a run that
* ended before it began (its container did not start, or stopped under it) has those alone. */
export function stepsOf(state: Run): RunStep[] {
const steps: RunStep[] = [];
for (const line of state.lines || []) {
const id = /^== step (\w+)/.exec(line)?.[1];
if (id) steps.push({ id, lines: [] });
else if (steps.length) steps.at(-1)!.lines.push(line);
else steps.push({ id: "", lines: [line] });
}
return steps;
}
/** The step at which a failed run stopped: null for a run that did not fail, "" for one that
* failed before its first step. */
export function failedStepOf(state: Run): string | null {
if (state.status !== "failed") return null;
if (state.failedAt) return state.failedAt;
return (
stepsOf(state)
.filter((s) => s.id !== FORGET)
.at(-1)?.id ?? ""
);
}
/** How far the step `id` is. After a failure the steps before the failed one are done, and so is
* "forget"; the steps that the run did not reach are still to do. */
export function phaseOf(state: Run, id: string): Phase {
const reached = stepsOf(state).map((s) => s.id);
if (!reached.includes(id)) return "todo";
if (state.status === "failed") return id === failedStepOf(state) ? "failed" : "done";
return state.status === "running" && reached.at(-1) === id ? "now" : "done";
}
/** A deploy's own error lines: the stack's (`[EmailRouting] fail — Forbidden: …`, `ERROR: …`). */
const ERROR = /\bfail —|\bERROR\b|Error:|^✗|^OwnedBySomeoneElse\b/;
/** Without the clock and the level that the stack's logger puts first. */
const bare = (line: string) =>
line.replace(/^\[\d\d:\d\d:\d\d(\.\d+)?\]\s*/, "").replace(/^ERROR(\s*\(#\d+\))?:\s*/, "");
/** The stack's names for its parts, in a person's words. */
const PART: Record<string, string> = {
ApexRecord: "the DNS record of your domain",
WildcardRecord: "the DNS record for every name under your domain",
EmailSending: "Email Sending for your domain",
EmailRouting: "Email Routing for your domain",
EmailCatchAll: "the mail rule of your domain",
};
/** An error line for a person: the deploy tool's own advice ("Re-run with --adopt") is for whoever
* runs the tool, never for the page. A part that exists already and was not taken up is said in
* plain words; the run takes such parts up itself, so this is the rare case where it could not. */
export function plainError(line: string): string {
const owned =
/Cannot adopt resource ['"`]?(\w+)/.exec(line) ||
/\[(\w+)\][^\n]*OwnedBySomeoneElse/.exec(line);
if (owned || /OwnedBySomeoneElse/.test(line)) {
const part = owned ? PART[owned[1]] || `the part “${owned[1]}”` : "a part of iterate";
return `Your Cloudflare account already has ${part}, and the deploy could not take it over. Press Try again. If it happens again, send us the deploy log.`;
}
// A route has one Worker. The run frees the routes of an earlier iterate before the deploy and
// stops at anybody else's (container/run.sh `routes_free`), so this is a route made in between.
const route =
/Cannot attach route (\S+) to Worker \S+ it is already attached to Worker ([\w-]+)/.exec(line);
if (route)
return `${route[1]} is served by your Worker “${route[2]}”, so iterate cannot serve it. In Cloudflare, open your domain, Workers Routes, and delete that route. Then press Try again.`;
return line.replace(/\s*Re-run with `?--adopt\b.*$/i, "").trim();
}
/** What a run that worked wants the person to know ("Note: …", from container/run.sh). */
export function notesOf(state: Pick<DeployState, "lines">): string[] {
return (state.lines || []).filter((l) => l.startsWith("Note: ")).map((l) => l.slice(6));
}
/** What went wrong in a failed run, in the run's own words: the run's own stop ("Stopped: …", from
* container/run.sh, shown alone), or the parts that the run found missing
* (container/check-result.sh says "Missing: …") and the error lines of the step that failed (the
* last three), or else the last thing that step said. "" for a run that did not fail. */
export function runErrorOf(state: Run): string {
const id = failedStepOf(state);
// oxlint-disable-next-line iterate/simple-truthiness-check -- failedStepOf gives "" for a failed run with no known step, which must still be described; only null means the run did not fail
if (id === null) return "";
const steps = stepsOf(state);
const lines = steps.find((s) => s.id === id)?.lines || [];
const stops = (of: string[]) =>
of.filter((l) => l.startsWith("Stopped: ")).map((l) => l.slice(9));
// an access that could not be given up is said after any other failure, too
const access = id === FORGET ? [] : stops(steps.find((s) => s.id === FORGET)?.lines || []);
const stopped = stops(lines);
if (stopped.length) return [...stopped, ...access].join("\n");
const missing = lines.filter((l) => l.startsWith("Missing: "));
const errors = [
...new Set(
lines
.filter((l) => ERROR.test(l))
.map(bare)
.map(plainError),
),
].slice(-3);
return [...missing, ...errors, ...access].join("\n") || lines.at(-1) || "";
}
/** The pages of a deployment that the person's page links to, by the id the run gives each, in
* the order the page names those that are not there. */
export const PAGES = ["dash", "keys", "self-test", "members", "mcp"] as const;
export type PageId = (typeof PAGES)[number];
/** Which of them answered. A page with no entry was not looked at, and counts as not there. */
export type Pages = Partial<Record<PageId, "works" | "missing">>;
/** What the run saw of those pages: its lines `page <id> works` and `page <id> missing`
* (container/check-result.sh, part 8). Null for a run that looked at none: one from before the
* run looked, whose pages somebody has to look at now. */
export function pagesOf(state: Pick<DeployState, "lines">): Pages | null {
const pages: Pages = {};
for (const line of state.lines || []) {
const [, id, answer] = /^page ([a-z-]+) (works|missing)$/.exec(line) || [];
const known = PAGES.find((page) => page === id);
if (known) pages[known] = answer === "works" ? "works" : "missing";
}
return Object.keys(pages).length ? pages : null;
}
/** The run, to paste into a coding agent: where it deployed, how it ended, what the page says went
* wrong, and every line the run printed. */
export function reportOf(
state: Pick<DeployState, "status" | "lines" | "steps" | "startedAt" | "endedAt">,
domain: string,
): string {
const at = failedStepOf(state);
const step = state.steps.find((s) => s.id === at)?.label;
const how = {
idle: "has not started",
running: "is still running",
succeeded: "worked",
failed: step ? `failed at the step “${step}”` : "failed before its first step",
}[state.status];
const iso = (ms: number) => new Date(ms).toISOString();
const error = runErrorOf(state);
return [
`iterate Cloud (https://cloud.iterate.com) ran a deploy of iterate to ${domain}, in my own Cloudflare account. It ${how}.`,
error && `What the page says went wrong:\n${error}`,
state.startedAt &&
`Started ${iso(state.startedAt)}${state.endedAt ? `, ended ${iso(state.endedAt)}` : ""}.`,
`The deploy log:\n\`\`\`text\n${(state.lines || []).join("\n")}\n\`\`\``,
]
.filter(Boolean)
.join("\n\n");
}