AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(deploy): preserve Cloudflare failure diagnostics
tianma-if3743cf4adb7b
diff --git a/scripts/run-wrangler.mjs b/scripts/run-wrangler.mjsindex 1b163f5c..fc7515e1 100644--- a/scripts/run-wrangler.mjs+++ b/scripts/run-wrangler.mjs@@ -15,6 +15,7 @@ import {findD1DatabaseIdByName,normalizeD1MigrationSql,parseWranglerDeploymentUrls,+ parseWranglerDeploymentVersionId,PLACEHOLDER_D1_ID,productionVersionIds,repositoryWranglerConfigError,@@ -466,8 +467,10 @@ if (captureDeploymentTargets) {if (result.stdout) process.stdout.write(result.stdout);if (result.stderr) process.stderr.write(result.stderr);if (result.status === 0) {- const urls = parseWranglerDeploymentUrls(`${result.stdout ?? ""}\n${result.stderr ?? ""}`);- writeFileSync(deploymentTargetsPath, `${JSON.stringify({ urls }, null, 2)}\n`);+ const deploymentOutput = `${result.stdout ?? ""}\n${result.stderr ?? ""}`;+ const urls = parseWranglerDeploymentUrls(deploymentOutput);+ const versionId = parseWranglerDeploymentVersionId(deploymentOutput);+ writeFileSync(deploymentTargetsPath, `${JSON.stringify({ urls, versionId }, null, 2)}\n`);}}diff --git a/scripts/verify-deployment.mjs b/scripts/verify-deployment.mjsindex 0e263ccc..df590a97 100644--- a/scripts/verify-deployment.mjs+++ b/scripts/verify-deployment.mjs@@ -82,16 +82,29 @@ export const normalizeDeploymentUrl = (value) => {return url.origin;};-export const parseCapturedDeploymentUrls = (content) => {+export const parseCapturedDeploymentTargets = (content) => {const parsed = parseJsonOutput(content, "the deployed Worker targets");if (!Array.isArray(parsed?.urls) || parsed.urls.some((url) => typeof url !== "string")) {throw new Error("Wrangler returned an invalid deployed Worker targets file.");}- return parsed.urls.map((url) => normalizeDeploymentUrl(url)).filter(Boolean);+ if (parsed.versionId !== undefined && typeof parsed.versionId !== "string") {+ throw new Error("Wrangler returned an invalid deployed Worker version ID.");+ }+ return {+ urls: parsed.urls.map((url) => normalizeDeploymentUrl(url)).filter(Boolean),+ versionId: parsed.versionId?.trim() || undefined,+ };};+export const parseCapturedDeploymentUrls = (content) => parseCapturedDeploymentTargets(content).urls;++export const readCapturedDeploymentTargets = (path = resolve(DEPLOYMENT_TARGETS_PATH)) =>+ existsSync(path)+ ? parseCapturedDeploymentTargets(readFileSync(path, "utf8"))+ : { urls: [], versionId: undefined };+export const readCapturedDeploymentUrls = (path = resolve(DEPLOYMENT_TARGETS_PATH)) =>- existsSync(path) ? parseCapturedDeploymentUrls(readFileSync(path, "utf8")) : [];+ readCapturedDeploymentTargets(path).urls;export const resolveDeploymentUrl = ({ env = process.env, capturedUrls = [] } = {}) => {const configuredUrl = instanceEnvironmentValue(env, "DEPLOYMENT_URL");@@ -105,8 +118,32 @@ export const resolveDeploymentUrl = ({ env = process.env, capturedUrls = [] } =const wait = (durationMs) => new Promise((resolveWait) => setTimeout(resolveWait, durationMs));-export const verifyOnlineHealth = async ({+const summarizeHealthResponseBody = (body, maxLength = 500) => {+ const normalized = body.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();+ if (!normalized) return undefined;+ return normalized.length > maxLength+ ? `${normalized.slice(0, maxLength)}…`+ : normalized;+};++const healthFailureContext = ({ body, deploymentVersionId, response }) => {+ const details = [];+ const responseBody = summarizeHealthResponseBody(body);+ const cfRay = response.headers.get("cf-ray")?.trim();++ if (responseBody) details.push(`response body: ${responseBody}`);+ if (cfRay) details.push(`CF-Ray: ${cfRay}`);+ if (deploymentVersionId) details.push(`Worker Version ID: ${deploymentVersionId}`);+ details.push(+ "Inspect Cloudflare Workers & Pages > edgeever > Logs > Live for the uncaught exception and stack trace, then retry the request.",+ );++ return details.join("; ");+};++export const verifyCloudflareWorkerHealth = async ({deploymentUrl,+ deploymentVersionId,fetchImpl = fetch,attempts = 4,retryDelayMs = 1_000,@@ -146,7 +183,10 @@ export const verifyOnlineHealth = async ({);} else {const diagnostic = payload?.error?.code || `${response.status} ${response.statusText}`.trim();- lastFailure = new Error(`Deployed Worker health check failed at ${healthUrl}: ${diagnostic}.`);+ const context = healthFailureContext({ body, deploymentVersionId, response });+ lastFailure = new Error(+ `Deployed Worker health check failed at ${healthUrl}: ${diagnostic}; ${context}`,+ );}} catch (error) {const message = error instanceof Error ? error.message : String(error);@@ -207,8 +247,8 @@ const main = async () => {}console.log("[ok] Worker authentication Secret is deployed");- const capturedUrls = readCapturedDeploymentUrls();- const deploymentUrl = resolveDeploymentUrl({ capturedUrls });+ const capturedTargets = readCapturedDeploymentTargets();+ const deploymentUrl = resolveDeploymentUrl({ capturedUrls: capturedTargets.urls });if (!deploymentUrl) {if (process.env.CI?.trim().toLowerCase() === "true" || process.env.WORKERS_CI === "1") {throw new Error(@@ -219,8 +259,14 @@ const main = async () => {return;}- const health = await verifyOnlineHealth({ deploymentUrl });- console.log(`[ok] deployed Worker health: ${health.healthUrl}`);+ const health = await verifyCloudflareWorkerHealth({+ deploymentUrl,+ deploymentVersionId: capturedTargets.versionId,+ });+ const versionDiagnostic = capturedTargets.versionId+ ? ` (Worker Version ID: ${capturedTargets.versionId})`+ : "";+ console.log(`[ok] deployed Worker health: ${health.healthUrl}${versionDiagnostic}`);};if (import.meta.main) {diff --git a/scripts/wrangler-runner.mjs b/scripts/wrangler-runner.mjsindex af83535a..170bc6e0 100644--- a/scripts/wrangler-runner.mjs+++ b/scripts/wrangler-runner.mjs@@ -101,6 +101,11 @@ export const parseWranglerDeploymentUrls = (output) => {return urls;};+export const parseWranglerDeploymentVersionId = (output) => {+ const matches = [...stripAnsi(output).matchAll(/^Current Version ID:\s*(\S+)\s*$/gim)];+ return matches.at(-1)?.[1];+};+export const shouldCaptureDeploymentTargets = (env = process.env) =>env.WORKERS_CI === "1" || env.CI?.trim().toLowerCase() === "true";diff --git a/tests/deployment-entrypoints.test.ts b/tests/deployment-entrypoints.test.tsindex 4f6f6b90..dd159d7c 100644--- a/tests/deployment-entrypoints.test.ts+++ b/tests/deployment-entrypoints.test.ts@@ -358,7 +358,10 @@ describe("Cloudflare deployment entrypoints", () => {expect(JSON.parse(readFileSync(resolve(workingDirectory, ".wrangler.deployment-targets.json"),"utf8",- ))).toEqual({ urls: ["https://edgeever.example.workers.dev"] });+ ))).toEqual({+ urls: ["https://edgeever.example.workers.dev"],+ versionId: "version-1",+ });const generatedConfig = readFileSync(resolve(workingDirectory, ".wrangler.generated.toml"),"utf8",diff --git a/tests/deployment-verify.test.ts b/tests/deployment-verify.test.tsindex 150b07b6..d66fda33 100644--- a/tests/deployment-verify.test.ts+++ b/tests/deployment-verify.test.ts@@ -2,16 +2,18 @@ import { describe, expect, test } from "bun:test";import {buildSchemaVerificationSql,normalizeDeploymentUrl,+ parseCapturedDeploymentTargets,parseCapturedDeploymentUrls,parseD1Rows,parseJsonOutput,parseSecretNames,REQUIRED_TABLES,resolveDeploymentUrl,- verifyOnlineHealth,+ verifyCloudflareWorkerHealth,} from "../scripts/verify-deployment.mjs";import {parseWranglerDeploymentUrls,+ parseWranglerDeploymentVersionId,shouldCaptureDeploymentTargets,} from "../scripts/wrangler-runner.mjs";@@ -58,6 +60,10 @@ describe("deployment verification", () => {"https://notes.example.com",]);expect(parseWranglerDeploymentUrls("No targets deployed for edgeever")).toEqual([]);+ expect(parseWranglerDeploymentVersionId([+ "Uploaded edgeever (2.1 sec)",+ "Current Version ID: version-1",+ ].join("\n"))).toBe("version-1");});test("captures deployment targets only in CI environments", () => {@@ -71,6 +77,13 @@ describe("deployment verification", () => {expect(parseCapturedDeploymentUrls(JSON.stringify({urls: ["https://edgeever.example.workers.dev"],}))).toEqual(["https://edgeever.example.workers.dev"]);+ expect(parseCapturedDeploymentTargets(JSON.stringify({+ urls: ["https://edgeever.example.workers.dev"],+ versionId: "version-1",+ }))).toEqual({+ urls: ["https://edgeever.example.workers.dev"],+ versionId: "version-1",+ });expect(resolveDeploymentUrl({env: { EDGE_EVER_DEPLOYMENT_URL: "https://notes.example.com/app" },capturedUrls: ["https://edgeever.example.workers.dev"],@@ -84,7 +97,7 @@ describe("deployment verification", () => {test("verifies the live Worker health response", async () => {let requestedUrl = "";- const result = await verifyOnlineHealth({+ const result = await verifyCloudflareWorkerHealth({deploymentUrl: "https://notes.example.com",attempts: 1,fetchImpl: async (url) => {@@ -98,13 +111,13 @@ describe("deployment verification", () => {});test("requires a URL before requesting the live Worker", async () => {- expect(verifyOnlineHealth({ deploymentUrl: "" })).rejects.toThrow(+ expect(verifyCloudflareWorkerHealth({ deploymentUrl: "" })).rejects.toThrow("A deployment URL is required",);});test("diagnoses a live Worker bound to a different unprepared D1 database", async () => {- expect(verifyOnlineHealth({+ expect(verifyCloudflareWorkerHealth({deploymentUrl: "https://notes.example.com",attempts: 1,fetchImpl: async () => Response.json({@@ -114,7 +127,7 @@ describe("deployment verification", () => {});test("diagnoses a live Worker without its R2 binding", async () => {- expect(verifyOnlineHealth({+ expect(verifyCloudflareWorkerHealth({deploymentUrl: "https://notes.example.com",attempts: 1,fetchImpl: async () => Response.json({@@ -122,4 +135,22 @@ describe("deployment verification", () => {}, { status: 503 }),})).rejects.toThrow("RESOURCES binding points to the configured R2 bucket");});++ test("preserves Cloudflare runtime diagnostics for an unknown health failure", async () => {+ const verification = verifyCloudflareWorkerHealth({+ deploymentUrl: "https://notes.example.com",+ deploymentVersionId: "version-1101",+ attempts: 1,+ fetchImpl: async () => new Response("error code: 1101", {+ status: 500,+ statusText: "Internal Server Error",+ headers: { "CF-Ray": "ray-id-SJC" },+ }),+ });++ await expect(verification).rejects.toThrow("response body: error code: 1101");+ await expect(verification).rejects.toThrow("CF-Ray: ray-id-SJC");+ await expect(verification).rejects.toThrow("Worker Version ID: version-1101");+ await expect(verification).rejects.toThrow("Logs > Live");+ });});