-
Notifications
You must be signed in to change notification settings - Fork 73
fix: make sure that fetch cache sets are properly awaited #364
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
Changes from 2 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
61484b6
fix: make sure that fetch cache `set`s are properly awaited
dario-piotrowicz 6166646
apply more strict filtering
dario-piotrowicz 05f7225
update filtering
dario-piotrowicz 984f22d
use `getCrossPlatformPathRegex`
dario-piotrowicz c6ccf77
fix imports ordering
dario-piotrowicz 9e5b1bb
apply a single rule
dario-piotrowicz 5af6349
update tests
dario-piotrowicz d169c6a
remove extra line
dario-piotrowicz 1a6baa2
get everything to work with a single rule
dario-piotrowicz 669d67c
Update packages/cloudflare/src/cli/build/patches/plugins/fetch-cache-…
dario-piotrowicz 5e97964
revert `getCrossPlatformPathRegex` usage
dario-piotrowicz bd15f56
Revert "revert `getCrossPlatformPathRegex` usage"
dario-piotrowicz 7ed84ee
reset `filter.lastIndex` in content-updater
dario-piotrowicz 96d7162
fix typo
dario-piotrowicz 107b285
use `match` instead of resetting the regex
dario-piotrowicz 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
--- | ||
"@opennextjs/cloudflare": patch | ||
--- | ||
|
||
fix: make sure that fetch cache `set`s are properly awaited | ||
|
||
Next.js does not await promises that update the incremental cache for fetch requests, | ||
that is needed in our runtime otherwise the cache updates get lost, so this change | ||
makes sure that the promise is properly awaited via `waitUntil` |
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
107 changes: 107 additions & 0 deletions
107
packages/cloudflare/src/cli/build/patches/plugins/fetch-cache-wait-until.spec.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,107 @@ | ||
import { describe, expect, test } from "vitest"; | ||
|
||
import { patchCode } from "../ast/util.js"; | ||
import { ruleForMinifiedCode, ruleForNonMinifiedCode } from "./fetch-cache-wait-until.js"; | ||
|
||
describe("patchFetchCacheSetMissingWaitUntil", () => { | ||
test("on minified code", () => { | ||
const code = ` | ||
{ | ||
let [o4, a2] = (0, d2.cloneResponse)(e3); | ||
return o4.arrayBuffer().then(async (e4) => { | ||
dario-piotrowicz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
var a3; | ||
let i4 = Buffer.from(e4), s3 = { headers: Object.fromEntries(o4.headers.entries()), body: i4.toString("base64"), status: o4.status, url: o4.url }; | ||
null == $ || null == (a3 = $.serverComponentsHmrCache) || a3.set(n2, s3), F && await H.set(n2, { kind: c2.CachedRouteKind.FETCH, data: s3, revalidate: t5 }, { fetchCache: true, revalidate: r4, fetchUrl: _, fetchIdx: q, tags: A2 }); | ||
}).catch((e4) => console.warn("Failed to set fetch cache", u4, e4)).finally(X), a2; | ||
}`; | ||
|
||
expect(patchCode(code, ruleForMinifiedCode)).toMatchInlineSnapshot(` | ||
"{ | ||
let [o4, a2] = (0, d2.cloneResponse)(e3); | ||
globalThis.__openNextAls?.getStore()?.waitUntil?.(o4.arrayBuffer().then(async (e4) => { | ||
var a3; | ||
let i4 = Buffer.from(e4), s3 = { headers: Object.fromEntries(o4.headers.entries()), body: i4.toString("base64"), status: o4.status, url: o4.url }; | ||
null == $ || null == (a3 = $.serverComponentsHmrCache) || a3.set(n2, s3), F && await H.set(n2, { kind: c2.CachedRouteKind.FETCH, data: s3, revalidate: t5 }, { fetchCache: true, revalidate: r4, fetchUrl: _, fetchIdx: q, tags: A2 }); | ||
}).catch((e4) => console.warn("Failed to set fetch cache", u4, e4)).finally(X)); | ||
return a2; | ||
|
||
}" | ||
`); | ||
}); | ||
|
||
test("on non-minified code", () => { | ||
const code = ` | ||
// We're cloning the response using this utility because there | ||
// exists a bug in the undici library around response cloning. | ||
// See the following pull request for more details: | ||
// https://github.com/vercel/next.js/pull/73274 | ||
const [cloned1, cloned2] = (0, _cloneresponse.cloneResponse)(res); | ||
// We are dynamically rendering including dev mode. We want to return | ||
// the response to the caller as soon as possible because it might stream | ||
// over a very long time. | ||
cloned1.arrayBuffer().then(async (arrayBuffer)=>{ | ||
var _requestStore_serverComponentsHmrCache; | ||
const bodyBuffer = Buffer.from(arrayBuffer); | ||
const fetchedData = { | ||
headers: Object.fromEntries(cloned1.headers.entries()), | ||
body: bodyBuffer.toString('base64'), | ||
status: cloned1.status, | ||
url: cloned1.url | ||
}; | ||
requestStore == null ? void 0 : (_requestStore_serverComponentsHmrCache = requestStore.serverComponentsHmrCache) == null ? void 0 : _requestStore_serverComponentsHmrCache.set(cacheKey, fetchedData); | ||
if (isCacheableRevalidate) { | ||
await incrementalCache.set(cacheKey, { | ||
kind: _responsecache.CachedRouteKind.FETCH, | ||
data: fetchedData, | ||
revalidate: normalizedRevalidate | ||
}, { | ||
fetchCache: true, | ||
revalidate: externalRevalidate, | ||
fetchUrl, | ||
fetchIdx, | ||
tags | ||
}); | ||
} | ||
}).catch((error)=>console.warn(\`Failed to set fetch cache\`, input, error)).finally(handleUnlock); | ||
return cloned2; | ||
`; | ||
|
||
expect(patchCode(code, ruleForNonMinifiedCode)).toMatchInlineSnapshot(` | ||
"// We're cloning the response using this utility because there | ||
// exists a bug in the undici library around response cloning. | ||
// See the following pull request for more details: | ||
// https://github.com/vercel/next.js/pull/73274 | ||
const [cloned1, cloned2] = (0, _cloneresponse.cloneResponse)(res); | ||
// We are dynamically rendering including dev mode. We want to return | ||
// the response to the caller as soon as possible because it might stream | ||
// over a very long time. | ||
globalThis.__openNextAls?.getStore()?.waitUntil?.(cloned1.arrayBuffer().then(async (arrayBuffer)=>{ | ||
var _requestStore_serverComponentsHmrCache; | ||
const bodyBuffer = Buffer.from(arrayBuffer); | ||
const fetchedData = { | ||
headers: Object.fromEntries(cloned1.headers.entries()), | ||
body: bodyBuffer.toString('base64'), | ||
status: cloned1.status, | ||
url: cloned1.url | ||
}; | ||
requestStore == null ? void 0 : (_requestStore_serverComponentsHmrCache = requestStore.serverComponentsHmrCache) == null ? void 0 : _requestStore_serverComponentsHmrCache.set(cacheKey, fetchedData); | ||
if (isCacheableRevalidate) { | ||
await incrementalCache.set(cacheKey, { | ||
kind: _responsecache.CachedRouteKind.FETCH, | ||
data: fetchedData, | ||
revalidate: normalizedRevalidate | ||
}, { | ||
fetchCache: true, | ||
revalidate: externalRevalidate, | ||
fetchUrl, | ||
fetchIdx, | ||
tags | ||
}); | ||
} | ||
}).catch((error)=>console.warn(\`Failed to set fetch cache\`, input, error)).finally(handleUnlock)); | ||
|
||
return cloned2; | ||
" | ||
`); | ||
}); | ||
}); |
58 changes: 58 additions & 0 deletions
58
packages/cloudflare/src/cli/build/patches/plugins/fetch-cache-wait-until.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,58 @@ | ||
import { patchCode } from "../ast/util.js"; | ||
import type { ContentUpdater } from "./content-updater.js"; | ||
|
||
/** | ||
* The following Next.js code sets values in the incremental cache for fetch calls: | ||
* https://github.com/vercel/next.js/blob/e5fc495e3d4/packages/next/src/server/lib/patch-fetch.ts#L690-L728 | ||
* | ||
* The issue here is that this promise is never awaited in the Next.js code (since in a standard node.js server | ||
* the promise will eventually simply just run) but we do need to run it inside `waitUntil` (so that the worker | ||
* is not killed before the promise is fully executed), without that this promise gets discarded and values | ||
* don't get saved in the incremental cache. | ||
dario-piotrowicz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* | ||
* This function wraps the promise in a `waitUntil` call (retrieved from `globalThis.__openNextAls.getStore()`). | ||
*/ | ||
export function patchFetchCacheSetMissingWaitUntil(updater: ContentUpdater) { | ||
return updater.updateContent( | ||
"patch-fetch-cache-set-missing-wait-until", | ||
{ | ||
filter: /(server\/chunks\/.*\.js|.*\.runtime\..*\.js|patch-fetch\.js)$/, | ||
dario-piotrowicz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
contentFilter: /Failed to set fetch cache/, | ||
}, | ||
({ contents }) => { | ||
contents = patchCode(contents, ruleForMinifiedCode); | ||
return patchCode(contents, ruleForNonMinifiedCode); | ||
} | ||
); | ||
} | ||
|
||
export const ruleForMinifiedCode = ` | ||
dario-piotrowicz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
rule: | ||
pattern: return $PROMISE, $CLONED2 | ||
regex: Failed to set fetch cache | ||
follows: | ||
kind: lexical_declaration | ||
pattern: let [$CLONED1, $CLONED2] | ||
|
||
fix: | | ||
globalThis.__openNextAls?.getStore()?.waitUntil?.($PROMISE); | ||
return $CLONED2; | ||
`; | ||
|
||
export const ruleForNonMinifiedCode = ` | ||
dario-piotrowicz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
rule: | ||
regex: Failed to set fetch cache | ||
pattern: $PROMISE; | ||
follows: | ||
kind: comment | ||
follows: | ||
kind: comment | ||
follows: | ||
kind: comment | ||
dario-piotrowicz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
follows: | ||
kind: lexical_declaration | ||
pattern: const [cloned1, cloned2] | ||
|
||
fix: | | ||
globalThis.__openNextAls?.getStore()?.waitUntil?.($PROMISE); | ||
`; |
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.