Skip to content

Commit 0702d2e

Browse files
authored
feat: support passing the wrangler environment when populating the cache (#487)
1 parent 25a8f4c commit 0702d2e

File tree

9 files changed

+105
-39
lines changed

9 files changed

+105
-39
lines changed

.changeset/chilly-knives-taste.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@opennextjs/cloudflare": patch
3+
---
4+
5+
feat: support passing the wrangler environment when populating the cache

examples/common/config-e2e.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,14 @@ export function configurePlaywright(
2323
let command: string;
2424
let timeout: number;
2525
if (isWorker) {
26+
const env = app === "r2-incremental-cache" ? "--env e2e" : "";
2627
if (isCI) {
2728
// Do not build on CI - there is a preceding build step
28-
command = `pnpm preview:worker -- --port ${port} --inspector-port ${inspectorPort}`;
29+
command = `pnpm preview:worker -- --port ${port} --inspector-port ${inspectorPort} ${env}`;
2930
timeout = 100_000;
3031
} else {
3132
timeout = 500_000;
32-
command = `pnpm preview -- --port ${port} --inspector-port ${inspectorPort}`;
33+
command = `pnpm preview -- --port ${port} --inspector-port ${inspectorPort} ${env}`;
3334
}
3435
} else {
3536
timeout = 100_000;

examples/overrides/r2-incremental-cache/package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
"build": "next build",
88
"start": "next start",
99
"lint": "next lint",
10-
"d1:clean": "wrangler d1 execute NEXT_CACHE_D1 --command \"DROP TABLE IF EXISTS tags; DROP TABLE IF EXISTS revalidations\"",
11-
"build:worker": "pnpm d1:clean && pnpm opennextjs-cloudflare build",
10+
"build:worker": "pnpm opennextjs-cloudflare build",
1211
"preview:worker": "pnpm opennextjs-cloudflare preview",
1312
"preview": "pnpm build:worker && pnpm preview:worker",
1413
"e2e": "playwright test -c e2e/playwright.config.ts"

examples/overrides/r2-incremental-cache/wrangler.jsonc

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,31 @@
88
"directory": ".open-next/assets",
99
"binding": "ASSETS"
1010
},
11-
"d1_databases": [
12-
{
13-
"binding": "NEXT_CACHE_D1",
14-
"database_id": "NEXT_CACHE_D1",
15-
"database_name": "NEXT_CACHE_D1"
11+
"env": {
12+
"e2e": {
13+
"d1_databases": [
14+
{
15+
"binding": "NEXT_CACHE_D1",
16+
"database_id": "NEXT_CACHE_D1",
17+
"database_name": "NEXT_CACHE_D1"
18+
}
19+
],
20+
"services": [
21+
{
22+
"binding": "NEXT_CACHE_REVALIDATION_WORKER",
23+
"service": "r2-incremental-cache-e2e"
24+
}
25+
],
26+
"r2_buckets": [
27+
{
28+
"binding": "NEXT_CACHE_R2_BUCKET",
29+
"bucket_name": "NEXT_CACHE_R2_BUCKET",
30+
"preview_bucket_name": "NEXT_CACHE_R2_BUCKET"
31+
}
32+
]
33+
},
34+
"prod": {
35+
// left blank to test that environment configuration works properly
1636
}
17-
],
18-
"services": [
19-
{
20-
"binding": "NEXT_CACHE_REVALIDATION_WORKER",
21-
"service": "r2-incremental-cache"
22-
}
23-
],
24-
"r2_buckets": [
25-
{
26-
"binding": "NEXT_CACHE_R2_BUCKET",
27-
"bucket_name": "NEXT_CACHE_R2_BUCKET",
28-
"preview_bucket_name": "NEXT_CACHE_R2_BUCKET"
29-
}
30-
]
37+
}
3138
}

packages/cloudflare/src/cli/args.ts

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import { mkdirSync, type Stats, statSync } from "node:fs";
22
import { resolve } from "node:path";
33
import { parseArgs } from "node:util";
44

5-
import { isWranglerTarget, WranglerTarget } from "./utils/run-wrangler.js";
5+
import type { WranglerTarget } from "./utils/run-wrangler.js";
6+
import { getWranglerEnvironmentFlag, isWranglerTarget } from "./utils/run-wrangler.js";
67

78
export type Arguments = (
89
| {
@@ -11,8 +12,15 @@ export type Arguments = (
1112
skipWranglerConfigCheck: boolean;
1213
minify: boolean;
1314
}
14-
| { command: "preview" | "deploy"; passthroughArgs: string[] }
15-
| { command: "populateCache"; target: WranglerTarget }
15+
| {
16+
command: "preview" | "deploy";
17+
passthroughArgs: string[];
18+
}
19+
| {
20+
command: "populateCache";
21+
target: WranglerTarget;
22+
environment?: string;
23+
}
1624
) & { outputDir?: string };
1725

1826
export function getArgs(): Arguments {
@@ -29,6 +37,8 @@ export function getArgs(): Arguments {
2937
const outputDir = values.output ? resolve(values.output) : undefined;
3038
if (outputDir) assertDirArg(outputDir, "output", true);
3139

40+
const passthroughArgs = getPassthroughArgs();
41+
3242
switch (positionals[0]) {
3343
case "build":
3444
return {
@@ -43,12 +53,21 @@ export function getArgs(): Arguments {
4353
};
4454
case "preview":
4555
case "deploy":
46-
return { command: positionals[0], outputDir, passthroughArgs: getPassthroughArgs() };
56+
return {
57+
command: positionals[0],
58+
outputDir,
59+
passthroughArgs,
60+
};
4761
case "populateCache":
4862
if (!isWranglerTarget(positionals[1])) {
4963
throw new Error(`Error: invalid target for populating the cache, expected 'local' | 'remote'`);
5064
}
51-
return { command: "populateCache", outputDir, target: positionals[1] };
65+
return {
66+
command: "populateCache",
67+
outputDir,
68+
target: positionals[1],
69+
environment: getWranglerEnvironmentFlag(passthroughArgs),
70+
};
5271
default:
5372
throw new Error("Error: invalid command, expected 'build' | 'preview' | 'deploy' | 'populateCache'");
5473
}

packages/cloudflare/src/cli/deploy/deploy.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@ import { BuildOptions } from "@opennextjs/aws/build/helper.js";
22
import { OpenNextConfig } from "@opennextjs/aws/types/open-next.js";
33

44
import { populateCache } from "../populate-cache/populate-cache.js";
5-
import { runWrangler } from "../utils/run-wrangler.js";
5+
import { getWranglerEnvironmentFlag, runWrangler } from "../utils/run-wrangler.js";
66

77
export async function deploy(
88
options: BuildOptions,
99
config: OpenNextConfig,
1010
deployOptions: { passthroughArgs: string[] }
1111
) {
12-
await populateCache(options, config, { target: "remote" });
12+
await populateCache(options, config, {
13+
target: "remote",
14+
environment: getWranglerEnvironmentFlag(deployOptions.passthroughArgs),
15+
});
16+
1317
runWrangler(options, ["deploy", ...deployOptions.passthroughArgs], { logging: "all" });
1418
}

packages/cloudflare/src/cli/populate-cache/populate-cache.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ function getCacheAssetPaths(opts: BuildOptions) {
4646
export async function populateCache(
4747
options: BuildOptions,
4848
config: OpenNextConfig,
49-
populateCacheOptions: { target: WranglerTarget }
49+
populateCacheOptions: { target: WranglerTarget; environment?: string }
5050
) {
5151
const { incrementalCache, tagCache } = config.default.override ?? {};
5252

@@ -72,7 +72,9 @@ export async function populateCache(
7272
runWrangler(
7373
options,
7474
["r2 object put", JSON.stringify(fullDestPath), `--file ${JSON.stringify(fsPath)}`],
75-
{ ...populateCacheOptions, excludeRemoteFlag: true, logging: "error" }
75+
// NOTE: R2 does not support the environment flag and results in the following error:
76+
// Incorrect type for the 'cacheExpiry' field on 'HttpMetadata': the provided value is not of type 'date'.
77+
{ target: populateCacheOptions.target, excludeRemoteFlag: true, logging: "error" }
7678
);
7779
});
7880
logger.info(`Successfully populated cache with ${assets.length} assets`);

packages/cloudflare/src/cli/preview/preview.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@ import { BuildOptions } from "@opennextjs/aws/build/helper.js";
22
import { OpenNextConfig } from "@opennextjs/aws/types/open-next.js";
33

44
import { populateCache } from "../populate-cache/populate-cache.js";
5-
import { runWrangler } from "../utils/run-wrangler.js";
5+
import { getWranglerEnvironmentFlag, runWrangler } from "../utils/run-wrangler.js";
66

77
export async function preview(
88
options: BuildOptions,
99
config: OpenNextConfig,
1010
previewOptions: { passthroughArgs: string[] }
1111
) {
12-
await populateCache(options, config, { target: "local" });
12+
await populateCache(options, config, {
13+
target: "local",
14+
environment: getWranglerEnvironmentFlag(previewOptions.passthroughArgs),
15+
});
16+
1317
runWrangler(options, ["dev", ...previewOptions.passthroughArgs], { logging: "all" });
1418
}

packages/cloudflare/src/cli/utils/run-wrangler.ts

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,21 @@ import logger from "@opennextjs/aws/logger.js";
55

66
export type WranglerTarget = "local" | "remote";
77

8-
export function runWrangler(
9-
options: BuildOptions,
10-
args: string[],
11-
wranglerOpts: { target?: WranglerTarget; excludeRemoteFlag?: boolean; logging?: "all" | "error" } = {}
12-
) {
8+
type WranglerOptions = {
9+
target?: WranglerTarget;
10+
environment?: string;
11+
excludeRemoteFlag?: boolean;
12+
logging?: "all" | "error";
13+
};
14+
15+
export function runWrangler(options: BuildOptions, args: string[], wranglerOpts: WranglerOptions = {}) {
1316
const result = spawnSync(
1417
options.packager,
1518
[
1619
"exec",
1720
"wrangler",
1821
...args,
22+
wranglerOpts.environment && `--env ${wranglerOpts.environment}`,
1923
wranglerOpts.target === "remote" && !wranglerOpts.excludeRemoteFlag && "--remote",
2024
wranglerOpts.target === "local" && "--local",
2125
].filter((v): v is string => !!v),
@@ -34,3 +38,24 @@ export function runWrangler(
3438
export function isWranglerTarget(v: string | undefined): v is WranglerTarget {
3539
return !!v && ["local", "remote"].includes(v);
3640
}
41+
42+
/**
43+
* Find the value of the environment flag (`--env` / `-e`) used by Wrangler.
44+
*
45+
* @param args - CLI arguments.
46+
* @returns Value of the environment flag.
47+
*/
48+
export function getWranglerEnvironmentFlag(args: string[]) {
49+
for (let i = 0; i <= args.length; i++) {
50+
const arg = args[i];
51+
if (!arg) continue;
52+
53+
if (arg === "--env" || arg === "-e") {
54+
return args[i + 1];
55+
}
56+
57+
if (arg.startsWith("--env=") || arg.startsWith("-e=")) {
58+
return arg.split("=")[1];
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)