Skip to content
Draft
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
7 changes: 7 additions & 0 deletions .changeset/preview-build-output-missing-bindings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@cloudflare/deploy-helpers": patch
---

Warn when a Preview from Build Output is missing bindings that have no resource ID

`previewBuildOutput()` leaves out KV, D1, and R2 bindings without a resource ID so that the Preview can take them from the Preview base config. When the Preview base config doesn't define them either, the bindings were missing from the Preview without any warning, and code that used them failed at runtime. A warning now lists these bindings. It is written to stderr, so it also appears in JSON mode without changing the JSON output.
85 changes: 78 additions & 7 deletions packages/deploy-helpers/src/preview/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
import {
assemblePreviewScriptSettings,
extractBuildOutputBindings,
extractIdentifierlessBuildOutputBindings,
extractConfigBindings,
getBranchName,
getCommitSha,
Expand All @@ -51,6 +52,8 @@ import type {
Binding,
CreatePreviewDeploymentRequestParams,
DeploymentResource,
EnvBindings,
PreviewBaseConfig,
PreviewDeploymentModule,
PreviewResource,
} from "./api";
Expand Down Expand Up @@ -1000,6 +1003,15 @@ function logMissingCustomDomainPreviewUrlsWarning(
);
}

function formatBindingList(bindings: Record<string, { type: string }>) {
return Object.entries(bindings)
.map(
([name, binding]) =>
` ${chalk.cyan(name)} ${chalk.dim(getBindingTypeFriendlyName(binding.type as Parameters<typeof getBindingTypeFriendlyName>[0]))}`
)
.join("\n");
}

function logMissingPreviewsBindingsWarning(
productionBindingsExpectedInPreview: Record<string, { type: string }>,
remotePreviewDefaultBindings: Record<string, Binding> | undefined,
Expand All @@ -1021,19 +1033,71 @@ function logMissingPreviewsBindingsWarning(

logger.warn(`These bindings are configured for your production Worker but not for Previews:

${Object.entries(missingPreviewBindings)
.map(
([name, binding]) =>
` ${chalk.cyan(name)} ${chalk.dim(getBindingTypeFriendlyName(binding.type as Parameters<typeof getBindingTypeFriendlyName>[0]))}`
)
.join("\n")}
${formatBindingList(missingPreviewBindings)}

Parts of your Worker that depend on these bindings may not work correctly in the Preview. If this is not intentional, add Preview-safe values to the ${chalk.cyan("previews")} field.

Configuration: https://developers.cloudflare.com/workers/previews/configuration/
Resources: https://developers.cloudflare.com/workers/previews/resources/`);
}

/**
* Warns about Build Output bindings that were left out of a Preview for having
* no resource identifier and that the Preview base config doesn't define
* either, so they are missing from the Preview.
*
* @param config The Preview config used for API requests.
* @param accountId Account that owns the parent Worker.
* @param workerName The parent Worker name.
* @param identifierlessBindings Bindings left out of the Preview deployment.
*/
async function logMissingIdentifierlessBindingsWarning(
config: Config,
accountId: string,
workerName: string,
identifierlessBindings: EnvBindings
): Promise<void> {
if (Object.keys(identifierlessBindings).length === 0) {
return;
}

let previewBaseConfig: PreviewBaseConfig;
try {
previewBaseConfig = await getPreviewBaseConfig(
config,
accountId,
workerName
);
} catch {
// The deployment is already live, so a failed lookup for a warning
// shouldn't fail the command.
logger.warn(`These bindings have no resource ID, so they were left out of this Preview. The Preview base config could not be retrieved to check whether it defines them:

${formatBindingList(identifierlessBindings)}`);
return;
}
const missingBindings = Object.fromEntries(
Object.entries(identifierlessBindings).filter(
([name]) => !Object.hasOwn(previewBaseConfig.env ?? {}, name)
)
);

if (Object.keys(missingBindings).length === 0) {
return;
}

// Logged even with `--json`: the warning goes to stderr, so it can't corrupt
// the payload, and CI runs that parse the payload would otherwise never see it.
logger.warn(`These bindings have no resource ID, so they were left out of this Preview, and the Preview base config doesn't define them either:

${formatBindingList(missingBindings)}

Code that uses these bindings will fail in the Preview. Set a resource ID on these bindings for Previews, or add them to the Preview base config.

Configuration: https://developers.cloudflare.com/workers/previews/configuration/
Resources: https://developers.cloudflare.com/workers/previews/resources/`);
}

/**
* Creates the parent Worker required for a Preview, prompting when interactive.
*
Expand Down Expand Up @@ -1453,7 +1517,7 @@ export async function previewBuildOutput(
},
run_worker_first: convertedConfig.assets?.run_worker_first,
};
return runPreview(
const result = await runPreview(
accountId,
{ ...args, ignoreBaseConfig: false },
previewConfig,
Expand All @@ -1467,6 +1531,13 @@ export async function previewBuildOutput(
true,
localImageReferences
);
await logMissingIdentifierlessBindingsWarning(
previewConfig,
accountId,
workerConfig.name,
extractIdentifierlessBuildOutputBindings(convertedConfig)
);
return result;
}

/**
Expand Down
18 changes: 18 additions & 0 deletions packages/deploy-helpers/src/preview/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,24 @@ export function extractBuildOutputBindings(config: RawConfig): EnvBindings {
return extractBindings(config, config.assets, true);
}

/**
* Lists the resource bindings that `extractBuildOutputBindings` leaves out
* because they have no identifier to upload.
*
* @param config Wrangler config converted from Build Output.
* @returns The bindings left out, keyed by binding name.
*/
export function extractIdentifierlessBuildOutputBindings(
config: RawConfig
): EnvBindings {
const uploadedBindings = extractBuildOutputBindings(config);
return Object.fromEntries(
Object.entries(extractBindings(config, config.assets)).filter(
([name]) => !Object.hasOwn(uploadedBindings, name)
)
);
}

/**
* Returns the DO `class_name`s this script declares, through `migrations` or
* through `exports`, resolving them in the same order as wrangler's own
Expand Down
85 changes: 85 additions & 0 deletions packages/deploy-helpers/tests/preview-build-output.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import path from "node:path";
import { verifyDockerInstalled } from "@cloudflare/containers-shared";
import { runInTempDir } from "@cloudflare/workers-utils/test-helpers";
import { beforeEach, describe, it, vi } from "vitest";
import { stripAnsi } from "../src/preview/box";
import { previewBuildOutput } from "../src/preview/preview";
import { logger } from "../src/shared/context";
import type {
PreviewBuildOutput,
PreviewOptions,
Expand All @@ -19,6 +21,7 @@ const mocks = vi.hoisted(() => ({
createPreviewParentWorker: vi.fn(),
editPreview: vi.fn(),
getPreview: vi.fn(),
getPreviewBaseConfig: vi.fn(),
getPreviewDeployment: vi.fn(),
syncAssets: vi.fn(),
}));
Expand All @@ -30,6 +33,7 @@ vi.mock("../src/preview/api", async (importOriginal) => ({
createPreviewParentWorker: mocks.createPreviewParentWorker,
editPreview: mocks.editPreview,
getPreview: mocks.getPreview,
getPreviewBaseConfig: mocks.getPreviewBaseConfig,
getPreviewDeployment: mocks.getPreviewDeployment,
}));

Expand Down Expand Up @@ -104,6 +108,7 @@ describe("previewBuildOutput", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getPreview.mockResolvedValue(previewResource);
mocks.getPreviewBaseConfig.mockResolvedValue({});
mocks.getPreviewDeployment.mockResolvedValue(deploymentResource);
mocks.editPreview.mockResolvedValue(previewResource);
mocks.createPreview.mockResolvedValue(previewResource);
Expand Down Expand Up @@ -637,6 +642,86 @@ describe("previewBuildOutput", () => {
expect(request).not.toHaveProperty("env");
});

it("warns in JSON mode about bindings without identifiers that the Preview base config doesn't define", async ({
expect,
}) => {
mocks.getPreviewBaseConfig.mockResolvedValue({
env: { D1: { type: "d1", database_id: "base-d1-id" } },
});

await uploadPreview(
buildOutputConfig({
env: {
KV: { type: "kv" },
D1: { type: "d1" },
R2: { type: "r2" },
PREVIEW_KV: { type: "kv", id: "preview-kv-id" },
},
})
);

expect(mocks.getPreviewBaseConfig).toHaveBeenCalledWith(
expect.objectContaining({ name: "preview-worker" }),
"account-id",
"preview-worker"
);
expect(logger.warn).toHaveBeenCalledOnce();
expect(stripAnsi(String(vi.mocked(logger.warn).mock.calls[0]?.[0])))
.toMatchInlineSnapshot(`
"These bindings have no resource ID, so they were left out of this Preview, and the Preview base config doesn't define them either:

KV KV Namespace
R2 R2 Bucket

Code that uses these bindings will fail in the Preview. Set a resource ID on these bindings for Previews, or add them to the Preview base config.

Configuration: https://developers.cloudflare.com/workers/previews/configuration/
Resources: https://developers.cloudflare.com/workers/previews/resources/"
`);
});

it("does not warn when the Preview base config defines bindings without identifiers", async ({
expect,
}) => {
mocks.getPreviewBaseConfig.mockResolvedValue({
env: { KV: { type: "kv_namespace", namespace_id: "base-kv-id" } },
});

await uploadPreview(buildOutputConfig({ env: { KV: { type: "kv" } } }));

expect(logger.warn).not.toHaveBeenCalled();
});

it("still resolves when the Preview base config can't be read", async ({
expect,
}) => {
mocks.getPreviewBaseConfig.mockRejectedValue(new Error("Internal error"));

await expect(
uploadPreview(buildOutputConfig({ env: { KV: { type: "kv" } } }))
).resolves.toMatchObject({ deployment: deploymentResource });
expect(logger.warn).toHaveBeenCalledOnce();
expect(stripAnsi(String(vi.mocked(logger.warn).mock.calls[0]?.[0])))
.toMatchInlineSnapshot(`
"These bindings have no resource ID, so they were left out of this Preview. The Preview base config could not be retrieved to check whether it defines them:

KV KV Namespace"
`);
});

it("does not read the Preview base config when every binding has an identifier", async ({
expect,
}) => {
await uploadPreview(
buildOutputConfig({
env: { PREVIEW_KV: { type: "kv", id: "preview-kv-id" } },
})
);

expect(mocks.getPreviewBaseConfig).not.toHaveBeenCalled();
expect(logger.warn).not.toHaveBeenCalled();
});

it("keeps secrets from the latest deployment of an existing Preview", async ({
expect,
}) => {
Expand Down
Loading