Skip to content

feat: bulk insert cache entries to KV #626

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 2, 2025
Merged
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
5 changes: 5 additions & 0 deletions .changeset/wet-monkeys-look.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@opennextjs/cloudflare": patch
---

feat: bulk insert cache entries to KV
5 changes: 5 additions & 0 deletions packages/cloudflare/src/cli/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ export type Arguments = (
| {
command: "preview" | "deploy" | "upload";
passthroughArgs: string[];
cacheChunkSize?: number;
}
| {
command: "populateCache";
target: WranglerTarget;
environment?: string;
cacheChunkSize?: number;
}
) & { outputDir?: string };

Expand All @@ -30,6 +32,7 @@ export function getArgs(): Arguments {
output: { type: "string", short: "o" },
noMinify: { type: "boolean", default: false },
skipWranglerConfigCheck: { type: "boolean", default: false },
cacheChunkSize: { type: "string" },
},
allowPositionals: true,
});
Expand Down Expand Up @@ -58,6 +61,7 @@ export function getArgs(): Arguments {
command: positionals[0],
outputDir,
passthroughArgs,
...(values.cacheChunkSize && { cacheChunkSize: Number(values.cacheChunkSize) }),
};
case "populateCache":
if (!isWranglerTarget(positionals[1])) {
Expand All @@ -68,6 +72,7 @@ export function getArgs(): Arguments {
outputDir,
target: positionals[1],
environment: getWranglerEnvironmentFlag(passthroughArgs),
...(values.cacheChunkSize && { cacheChunkSize: Number(values.cacheChunkSize) }),
};
default:
throw new Error(
Expand Down
3 changes: 2 additions & 1 deletion packages/cloudflare/src/cli/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import { populateCache } from "./populate-cache.js";
export async function deploy(
options: BuildOptions,
config: OpenNextConfig,
deployOptions: { passthroughArgs: string[] }
deployOptions: { passthroughArgs: string[]; cacheChunkSize?: number }
) {
await populateCache(options, config, {
target: "remote",
environment: getWranglerEnvironmentFlag(deployOptions.passthroughArgs),
cacheChunkSize: deployOptions.cacheChunkSize,
});

runWrangler(options, ["deploy", ...deployOptions.passthroughArgs], { logging: "all" });
Expand Down
42 changes: 27 additions & 15 deletions packages/cloudflare/src/cli/commands/populate-cache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { cpSync, existsSync } from "node:fs";
import { cpSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";

import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
Expand Down Expand Up @@ -133,7 +133,7 @@ async function populateR2IncrementalCache(

async function populateKVIncrementalCache(
options: BuildOptions,
populateCacheOptions: { target: WranglerTarget; environment?: string }
populateCacheOptions: { target: WranglerTarget; environment?: string; cacheChunkSize?: number }
) {
logger.info("\nPopulating KV incremental cache...");

Expand All @@ -147,24 +147,36 @@ async function populateKVIncrementalCache(

const assets = getCacheAssets(options);

for (const { fullPath, key, buildId, isFetch } of tqdm(assets)) {
const cacheKey = computeCacheKey(key, {
prefix: proxy.env[KV_CACHE_PREFIX_ENV_NAME],
buildId,
cacheType: isFetch ? "fetch" : "cache",
});
const chunkSize = Math.max(1, populateCacheOptions.cacheChunkSize ?? 25);
const totalChunks = Math.ceil(assets.length / chunkSize);

logger.info(`Inserting ${assets.length} assets to KV in chunks of ${chunkSize}`);

for (const i of tqdm(Array.from({ length: totalChunks }, (_, i) => i))) {
const chunkPath = path.join(options.outputDir, "cloudflare", `cache-chunk-${i}.json`);

const kvMapping = assets
.slice(i * chunkSize, (i + 1) * chunkSize)
.map(({ fullPath, key, buildId, isFetch }) => ({
key: computeCacheKey(key, {
prefix: proxy.env[KV_CACHE_PREFIX_ENV_NAME],
buildId,
cacheType: isFetch ? "fetch" : "cache",
}),
value: readFileSync(fullPath, "utf8"),
}));

writeFileSync(chunkPath, JSON.stringify(kvMapping));

runWrangler(
options,
[
"kv key put",
JSON.stringify(cacheKey),
`--binding ${JSON.stringify(KV_CACHE_BINDING_NAME)}`,
`--path ${JSON.stringify(fullPath)}`,
],
["kv bulk put", JSON.stringify(chunkPath), `--binding ${JSON.stringify(KV_CACHE_BINDING_NAME)}`],
{ ...populateCacheOptions, logging: "error" }
);

rmSync(chunkPath);
}

logger.info(`Successfully populated cache with ${assets.length} assets`);
}

Expand Down Expand Up @@ -209,7 +221,7 @@ function populateStaticAssetsIncrementalCache(options: BuildOptions) {
export async function populateCache(
options: BuildOptions,
config: OpenNextConfig,
populateCacheOptions: { target: WranglerTarget; environment?: string }
populateCacheOptions: { target: WranglerTarget; environment?: string; cacheChunkSize?: number }
) {
const { incrementalCache, tagCache } = config.default.override ?? {};

Expand Down
3 changes: 2 additions & 1 deletion packages/cloudflare/src/cli/commands/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import { populateCache } from "./populate-cache.js";
export async function preview(
options: BuildOptions,
config: OpenNextConfig,
previewOptions: { passthroughArgs: string[] }
previewOptions: { passthroughArgs: string[]; cacheChunkSize?: number }
) {
await populateCache(options, config, {
target: "local",
environment: getWranglerEnvironmentFlag(previewOptions.passthroughArgs),
cacheChunkSize: previewOptions.cacheChunkSize,
});

runWrangler(options, ["dev", ...previewOptions.passthroughArgs], { logging: "all" });
Expand Down
3 changes: 2 additions & 1 deletion packages/cloudflare/src/cli/commands/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import { populateCache } from "./populate-cache.js";
export async function upload(
options: BuildOptions,
config: OpenNextConfig,
uploadOptions: { passthroughArgs: string[] }
uploadOptions: { passthroughArgs: string[]; cacheChunkSize?: number }
) {
await populateCache(options, config, {
target: "remote",
environment: getWranglerEnvironmentFlag(uploadOptions.passthroughArgs),
cacheChunkSize: uploadOptions.cacheChunkSize,
});

runWrangler(options, ["versions upload", ...uploadOptions.passthroughArgs], { logging: "all" });
Expand Down