Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 9 additions & 15 deletions pkgs/pkarr-worker/deploy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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%)`);
Expand Down
34 changes: 34 additions & 0 deletions pkgs/pkarr-worker/test/worker-exists.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
6 changes: 6 additions & 0 deletions pkgs/pkarr-worker/worker-exists.d.mts
Original file line number Diff line number Diff line change
@@ -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;
46 changes: 46 additions & 0 deletions pkgs/pkarr-worker/worker-exists.mjs
Original file line number Diff line number Diff line change
@@ -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;
}