-
Notifications
You must be signed in to change notification settings - Fork 70
feat: kv cache #194
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
feat: kv cache #194
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
afada27
feat: kv cache
vicb 4b9ad3c
Update packages/cloudflare/src/cli/build/index.ts
vicb 8ca0c07
fixup! delete, lastModified
vicb e6c6ded
fixup! feedback comment
vicb 05e8ae4
fixup! fetch cache
vicb cf3212e
fixup! cache support
vicb 7f72f9e
fixup! format
vicb 0612b61
fixup! Date.now()
vicb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
import type { KVNamespace } from "@cloudflare/workers-types"; | ||
import type { CacheValue, IncrementalCache, WithLastModified } from "@opennextjs/aws/types/overrides"; | ||
import { IgnorableError, RecoverableError } from "@opennextjs/aws/utils/error.js"; | ||
|
||
import { getCloudflareContext } from "./get-cloudflare-context.js"; | ||
|
||
export const CACHE_ASSET_DIR = "cnd-cgi/_next_cache"; | ||
|
||
export const STATUS_DELETED = 1; | ||
|
||
/** | ||
* Open Next cache based on cloudflare KV and Assets. | ||
* | ||
* Note: The class is instantiated outside of the request context. | ||
* The cloudflare context and process.env are not initialzed yet | ||
* when the constructor is called. | ||
*/ | ||
class Cache implements IncrementalCache { | ||
readonly name = "cloudflare-kv"; | ||
protected initialized = false; | ||
protected kv: KVNamespace | undefined; | ||
protected assets: Fetcher | undefined; | ||
|
||
async get<IsFetch extends boolean = false>( | ||
key: string, | ||
isFetch?: IsFetch | ||
): Promise<WithLastModified<CacheValue<IsFetch>>> { | ||
if (!this.initialized) { | ||
await this.init(); | ||
} | ||
|
||
if (!(this.kv || this.assets)) { | ||
throw new IgnorableError(`No KVNamespace nor Fetcher`); | ||
} | ||
|
||
this.debug(`Get ${key}`); | ||
|
||
try { | ||
let entry: { | ||
value?: CacheValue<IsFetch>; | ||
lastModified?: number; | ||
status?: number; | ||
} | null = null; | ||
|
||
if (this.kv) { | ||
this.debug(`- From KV`); | ||
const kvKey = this.getKVKey(key, isFetch); | ||
entry = await this.kv.get(kvKey, "json"); | ||
if (entry?.status === STATUS_DELETED) { | ||
return {}; | ||
} | ||
} | ||
|
||
if (!entry && this.assets) { | ||
this.debug(`- From Assets`); | ||
const url = this.getAssetUrl(key, isFetch); | ||
const response = await this.assets.fetch(url); | ||
if (response.ok) { | ||
// TODO: consider populating KV with the asset value if faster. | ||
// This could be optional as KV writes are $$. | ||
// See https://github.com/opennextjs/opennextjs-cloudflare/pull/194#discussion_r1893166026 | ||
entry = { | ||
value: await response.json(), | ||
// __BUILD_TIMESTAMP_MS__ is injected by ESBuild. | ||
lastModified: (globalThis as { __BUILD_TIMESTAMP_MS__?: number }).__BUILD_TIMESTAMP_MS__, | ||
}; | ||
} | ||
} | ||
this.debug(entry ? `-> hit` : `-> miss`); | ||
return { value: entry?.value, lastModified: entry?.lastModified }; | ||
} catch { | ||
throw new RecoverableError(`Failed to get cache [${key}]`); | ||
} | ||
} | ||
|
||
async set<IsFetch extends boolean = false>( | ||
key: string, | ||
value: CacheValue<IsFetch>, | ||
isFetch?: IsFetch | ||
): Promise<void> { | ||
if (!this.initialized) { | ||
await this.init(); | ||
} | ||
if (!this.kv) { | ||
throw new IgnorableError(`No KVNamespace`); | ||
} | ||
this.debug(`Set ${key}`); | ||
try { | ||
const kvKey = this.getKVKey(key, isFetch); | ||
// Note: We can not set a TTL as we might fallback to assets, | ||
// still removing old data (old BUILD_ID) could help avoiding | ||
// the cache growing too big. | ||
await this.kv.put( | ||
kvKey, | ||
JSON.stringify({ | ||
value, | ||
// Note: `Date.now()` returns the time of the last IO rather than the actual time. | ||
// See https://developers.cloudflare.com/workers/reference/security-model/ | ||
lastModified: Date.now(), | ||
}) | ||
); | ||
} catch { | ||
throw new RecoverableError(`Failed to set cache [${key}]`); | ||
} | ||
} | ||
|
||
async delete(key: string): Promise<void> { | ||
if (!this.initialized) { | ||
await this.init(); | ||
} | ||
if (!this.kv) { | ||
throw new IgnorableError(`No KVNamespace`); | ||
} | ||
this.debug(`Delete ${key}`); | ||
try { | ||
const kvKey = this.getKVKey(key, /* isFetch= */ false); | ||
// Do not delete the key as we would then fallback to the assets. | ||
await this.kv.put(kvKey, JSON.stringify({ status: STATUS_DELETED })); | ||
} catch { | ||
throw new RecoverableError(`Failed to delete cache [${key}]`); | ||
} | ||
} | ||
|
||
protected getKVKey(key: string, isFetch?: boolean): string { | ||
return `${this.getBuildId()}/${key}.${isFetch ? "fetch" : "cache"}`; | ||
} | ||
|
||
protected getAssetUrl(key: string, isFetch?: boolean): string { | ||
return isFetch | ||
? `http://assets.local/${CACHE_ASSET_DIR}/__fetch/${this.getBuildId()}/${key}` | ||
: `http://assets.local/${CACHE_ASSET_DIR}/${this.getBuildId()}/${key}.cache`; | ||
} | ||
|
||
protected debug(...args: unknown[]) { | ||
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { | ||
console.log(`[Cache ${this.name}] `, ...args); | ||
} | ||
} | ||
|
||
protected getBuildId() { | ||
return process.env.NEXT_BUILD_ID ?? "no-build-id"; | ||
} | ||
|
||
protected async init() { | ||
const env = (await getCloudflareContext()).env; | ||
this.kv = env.NEXT_CACHE_WORKERS_KV; | ||
this.assets = env.ASSETS; | ||
this.initialized = true; | ||
} | ||
} | ||
|
||
export default new Cache(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
packages/cloudflare/src/cli/build/open-next/copyCacheAssets.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { cpSync, mkdirSync } from "node:fs"; | ||
import { join } from "node:path"; | ||
|
||
import * as buildHelper from "@opennextjs/aws/build/helper.js"; | ||
|
||
import { CACHE_ASSET_DIR } from "../../../api/kvCache.js"; | ||
|
||
export function copyCacheAssets(options: buildHelper.BuildOptions) { | ||
const { outputDir } = options; | ||
const srcPath = join(outputDir, "cache"); | ||
const dstPath = join(outputDir, "assets", CACHE_ASSET_DIR); | ||
mkdirSync(dstPath, { recursive: true }); | ||
cpSync(srcPath, dstPath, { recursive: true }); | ||
} |
48 changes: 0 additions & 48 deletions
48
packages/cloudflare/src/cli/build/utils/copy-prerendered-routes.ts
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,3 @@ | ||
export * from "./copy-prerendered-routes.js"; | ||
export * from "./extract-project-env-vars.js"; | ||
export * from "./normalize-path.js"; | ||
export * from "./ts-parse-file.js"; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.