diff --git a/pkgs/pkarr-worker/deploy.mjs b/pkgs/pkarr-worker/deploy.mjs index ff84a785a9..2312b61dc9 100644 --- a/pkgs/pkarr-worker/deploy.mjs +++ b/pkgs/pkarr-worker/deploy.mjs @@ -31,6 +31,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { parseArgs } from "./deploy-args.mjs"; +import { workerExists } from "./worker-exists.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const WORKER = "pkarr"; @@ -87,7 +88,14 @@ const message = `deploy ${sha} via nix run .#pkarr-deploy`; // `cf deploy`, which creates the Worker's first version (with the // same tag/message) and its first deployment in one step. Every // later deploy uses the versions flow below. -const bootstrapping = !workerExists(); +const bootstrapping = !workerExists(WORKER, () => + execFileSync("cf", ["-q", "workers", "get", WORKER], { + cwd: here, + env, + encoding: "utf8", + stdio: ["inherit", "pipe", "pipe"], + }), +); if (bootstrapping) { const deployArgs = ["deploy", "--worker", WORKER, "--tag", tag, "--message", message]; if (dryRun) deployArgs.push("--dry-run"); @@ -132,20 +140,6 @@ if (bootstrapping) { reportLive(); console.log(`live: ${WORKER_URL} at version ${version.id} (${tag})`); -function workerExists() { - try { - execFileSync("cf", ["-q", "workers", "get", WORKER], { - cwd: here, - env, - encoding: "utf8", - stdio: ["inherit", "pipe", "pipe"], - }); - return true; - } catch { - return false; - } -} - function createDeployment(versionId) { const versions = JSON.stringify([{ version_id: versionId, percentage: 100 }]); console.log(`creating deployment at version ${versionId} (100%)`); diff --git a/pkgs/pkarr-worker/test/worker-exists.test.ts b/pkgs/pkarr-worker/test/worker-exists.test.ts new file mode 100644 index 0000000000..5ad86de12b --- /dev/null +++ b/pkgs/pkarr-worker/test/worker-exists.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; + +import { workerExists } from "../worker-exists.mjs"; + +function failedProbe(message: string, stderr = "") { + const error = new Error(message) as Error & { stderr?: Buffer }; + if (stderr) error.stderr = Buffer.from(stderr); + return error; +} + +describe("Cloudflare Worker existence probe", () => { + it("returns true when the probe succeeds", () => { + expect(workerExists("pkarr", () => ({ result: { id: "pkarr" } }))).toBe(true); + }); + + it("selects bootstrap only for cf's typed HTTP 404 response", () => { + const error = failedProbe( + "Command failed: cf -q workers get pkarr", + 'NotFoundError\nStatus code: 404\nBody: {"errors":[{"code":10007,"message":"Worker not found"}]}', + ); + + expect(workerExists("pkarr", () => { throw error; })).toBe(false); + }); + + it.each([ + ["authentication failure", failedProbe("ApiError", "Status code: 401\nBody: unauthorized"), /Status code: 401/], + ["permission failure", failedProbe("ApiError", "Status code: 403\nBody: forbidden"), /Status code: 403/], + ["unexpected 404", failedProbe("ApiError", "Status code: 404\nBody: unrelated endpoint"), /Status code: 404/], + ["network failure", failedProbe("connect ETIMEDOUT while probing Worker"), /ETIMEDOUT/], + ["missing cf executable", failedProbe("spawnSync cf ENOENT"), /ENOENT/], + ])("fails closed on %s", (_kind, error, diagnostic) => { + expect(() => workerExists("pkarr", () => { throw error; })).toThrow(diagnostic); + }); +}); diff --git a/pkgs/pkarr-worker/worker-exists.d.mts b/pkgs/pkarr-worker/worker-exists.d.mts new file mode 100644 index 0000000000..99a109f686 --- /dev/null +++ b/pkgs/pkarr-worker/worker-exists.d.mts @@ -0,0 +1,6 @@ +/** + * Check whether a Worker exists using a probe that throws on command failure. + * Only cf's typed HTTP 404 response means the Worker is absent; all other + * failures must stop deployment rather than select the bootstrap path. + */ +export function workerExists(workerName: string, probe: () => unknown): boolean; diff --git a/pkgs/pkarr-worker/worker-exists.mjs b/pkgs/pkarr-worker/worker-exists.mjs new file mode 100644 index 0000000000..dbdd4d8a44 --- /dev/null +++ b/pkgs/pkarr-worker/worker-exists.mjs @@ -0,0 +1,46 @@ +import { Buffer } from "node:buffer"; + +/** + * Check whether a Worker exists using a probe that throws on command failure. + * Only cf's typed HTTP 404 response means the Worker is absent; all other + * failures must stop deployment rather than select the bootstrap path. + * + * @param {string} workerName + * @param {() => unknown} probe + * @returns {boolean} + */ +export function workerExists(workerName, probe) { + try { + probe(); + return true; + } catch (error) { + const diagnostic = errorDiagnostic(error); + if (isWorkerNotFound(diagnostic)) return false; + + throw new Error( + `failed to probe Cloudflare Worker "${workerName}": ${diagnostic || "unknown error"}`, + { cause: error }, + ); + } +} + +function errorDiagnostic(error) { + const parts = [ + error?.stderr, + error?.stdout, + error instanceof Error ? error.message : String(error), + ].map(toText).filter(Boolean); + + return [...new Set(parts)].join("\n").trim(); +} + +function toText(value) { + if (Buffer.isBuffer(value)) return value.toString("utf8"); + return typeof value === "string" ? value : ""; +} + +function isWorkerNotFound(diagnostic) { + const typedNotFound = /\bNotFoundError\b/i.test(diagnostic); + const http404 = /\b(?:status code|statusCode|http(?:\/[\d.]+)?)\s*[:=]?\s*404\b/i.test(diagnostic); + return typedNotFound && http404; +}