Unverified Commit 86562e12 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[turbopack] Return cached Promise from `__turbopack_load_by_url__ ` (#81663)

parent af74b4a3
...@@ -346,6 +346,13 @@ export async function createHotReloaderTurbopack( ...@@ -346,6 +346,13 @@ export async function createHotReloaderTurbopack(
p.startsWith('server/app') p.startsWith('server/app')
) )
// Edge uses the browser runtime which already disposes chunks individually.
// TODO: process.env.NEXT_RUNTIME is 'nodejs' even though Node.js runtime is not used.
if ('__turbopack_clear_chunk_cache__' in globalThis) {
;(globalThis as any).__turbopack_clear_chunk_cache__()
}
// TODO: Stop re-evaluating React Client once it relies on Turbopack's chunk cache.
if (hasAppPaths) { if (hasAppPaths) {
deleteFromRequireCache( deleteFromRequireCache(
require.resolve( require.resolve(
......
...@@ -193,35 +193,43 @@ async function loadChunk( ...@@ -193,35 +193,43 @@ async function loadChunk(
return promise return promise
} }
async function loadChunkByUrl(source: SourceInfo, chunkUrl: ChunkUrl) { const instrumentedBackendLoadChunks = new WeakMap<Promise<any>, Promise<any>>()
try { // Do not make this async. React relies on referential equality of the returned Promise.
await BACKEND.loadChunk(chunkUrl, source) function loadChunkByUrl(source: SourceInfo, chunkUrl: ChunkUrl): Promise<any> {
} catch (error) { const thenable = BACKEND.loadChunk(chunkUrl, source)
let loadReason let entry = instrumentedBackendLoadChunks.get(thenable)
switch (source.type) { if (entry === undefined) {
case SourceType.Runtime: entry = thenable.catch((error) => {
loadReason = `as a runtime dependency of chunk ${source.chunkPath}` let loadReason
break switch (source.type) {
case SourceType.Parent: case SourceType.Runtime:
loadReason = `from module ${source.parentId}` loadReason = `as a runtime dependency of chunk ${source.chunkPath}`
break break
case SourceType.Update: case SourceType.Parent:
loadReason = 'from an HMR update' loadReason = `from module ${source.parentId}`
break break
default: case SourceType.Update:
invariant(source, (source) => `Unknown source type: ${source?.type}`) loadReason = 'from an HMR update'
} break
throw new Error( default:
`Failed to load chunk ${chunkUrl} ${loadReason}${ invariant(source, (source) => `Unknown source type: ${source?.type}`)
error ? `: ${error}` : '' }
}`, throw new Error(
error `Failed to load chunk ${chunkUrl} ${loadReason}${
? { error ? `: ${error}` : ''
cause: error, }`,
} error
: undefined ? {
) cause: error,
}
: undefined
)
})
// TODO: Free the Promise once it resolves.
instrumentedBackendLoadChunks.set(thenable, entry)
} }
return entry
} }
async function loadChunkPath( async function loadChunkPath(
......
...@@ -93,6 +93,13 @@ function loadChunk(chunkData: ChunkData, source?: SourceInfo): void { ...@@ -93,6 +93,13 @@ function loadChunk(chunkData: ChunkData, source?: SourceInfo): void {
} }
const loadedChunks = new Set<ChunkPath>() const loadedChunks = new Set<ChunkPath>()
const unsupportedLoadChunk = Promise.resolve(undefined)
const loadedChunk = Promise.resolve(undefined)
const chunkCache = new Map<ChunkPath, Promise<any> | null>()
function clearChunkCache() {
chunkCache.clear()
}
function loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void { function loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void {
if (!isJs(chunkPath)) { if (!isJs(chunkPath)) {
...@@ -136,21 +143,10 @@ function loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void { ...@@ -136,21 +143,10 @@ function loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void {
} }
} }
async function loadChunkAsync( async function loadChunkAsyncUncached(
source: SourceInfo, source: SourceInfo,
chunkData: ChunkData chunkPath: ChunkPath
): Promise<any> { ): Promise<void> {
const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return
}
if (loadedChunks.has(chunkPath)) {
return
}
const resolved = path.resolve(RUNTIME_ROOT, chunkPath) const resolved = path.resolve(RUNTIME_ROOT, chunkPath)
try { try {
...@@ -187,7 +183,6 @@ async function loadChunkAsync( ...@@ -187,7 +183,6 @@ async function loadChunkAsync(
} }
} }
} }
loadedChunks.add(chunkPath)
} catch (e) { } catch (e) {
let errorMessage = `Failed to load chunk ${chunkPath}` let errorMessage = `Failed to load chunk ${chunkPath}`
...@@ -201,7 +196,30 @@ async function loadChunkAsync( ...@@ -201,7 +196,30 @@ async function loadChunkAsync(
} }
} }
async function loadChunkAsyncByUrl(source: SourceInfo, chunkUrl: string) { function loadChunkAsync(
source: SourceInfo,
chunkData: ChunkData
): Promise<any> {
const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return unsupportedLoadChunk
}
let entry = chunkCache.get(chunkPath)
if (entry === undefined) {
const resolve = chunkCache.set.bind(chunkCache, chunkPath, null)
// A new Promise ensures callers that don't handle rejection will still trigger one unhandled rejection.
// Handling the rejection will not trigger unhandled rejections.
entry = loadChunkAsyncUncached(source, chunkPath).then(resolve)
chunkCache.set(chunkPath, entry)
}
// TODO: Return an instrumented Promise that React can use instead of relying on referential equality.
return entry === null ? loadedChunk : entry
}
function loadChunkAsyncByUrl(source: SourceInfo, chunkUrl: string) {
const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath
return loadChunkAsync(source, path) return loadChunkAsync(source, path)
} }
...@@ -363,6 +381,9 @@ function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean { ...@@ -363,6 +381,9 @@ function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
return regexJsUrl.test(chunkUrlOrPath) return regexJsUrl.test(chunkUrlOrPath)
} }
// For hot-reloader
;(globalThis as any).__turbopack_clear_chunk_cache__ = clearChunkCache
module.exports = { module.exports = {
getOrInstantiateRuntimeModule, getOrInstantiateRuntimeModule,
loadChunk, loadChunk,
......
...@@ -496,6 +496,12 @@ function loadChunk(chunkData, source) { ...@@ -496,6 +496,12 @@ function loadChunk(chunkData, source) {
} }
} }
const loadedChunks = new Set(); const loadedChunks = new Set();
const unsupportedLoadChunk = Promise.resolve(undefined);
const loadedChunk = Promise.resolve(undefined);
const chunkCache = new Map();
function clearChunkCache() {
chunkCache.clear();
}
function loadChunkPath(chunkPath, source) { function loadChunkPath(chunkPath, source) {
if (!isJs(chunkPath)) { if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js. // We only support loading JS chunks in Node.js.
...@@ -532,16 +538,7 @@ function loadChunkPath(chunkPath, source) { ...@@ -532,16 +538,7 @@ function loadChunkPath(chunkPath, source) {
}); });
} }
} }
async function loadChunkAsync(source, chunkData) { async function loadChunkAsyncUncached(source, chunkPath) {
const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path;
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return;
}
if (loadedChunks.has(chunkPath)) {
return;
}
const resolved = path.resolve(RUNTIME_ROOT, chunkPath); const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
try { try {
const contents = await fs.readFile(resolved, 'utf-8'); const contents = await fs.readFile(resolved, 'utf-8');
...@@ -571,7 +568,6 @@ async function loadChunkAsync(source, chunkData) { ...@@ -571,7 +568,6 @@ async function loadChunkAsync(source, chunkData) {
} }
} }
} }
loadedChunks.add(chunkPath);
} catch (e) { } catch (e) {
let errorMessage = `Failed to load chunk ${chunkPath}`; let errorMessage = `Failed to load chunk ${chunkPath}`;
if (source) { if (source) {
...@@ -582,7 +578,25 @@ async function loadChunkAsync(source, chunkData) { ...@@ -582,7 +578,25 @@ async function loadChunkAsync(source, chunkData) {
}); });
} }
} }
async function loadChunkAsyncByUrl(source, chunkUrl) { function loadChunkAsync(source, chunkData) {
const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path;
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return unsupportedLoadChunk;
}
let entry = chunkCache.get(chunkPath);
if (entry === undefined) {
const resolve = chunkCache.set.bind(chunkCache, chunkPath, null);
// A new Promise ensures callers that don't handle rejection will still trigger one unhandled rejection.
// Handling the rejection will not trigger unhandled rejections.
entry = loadChunkAsyncUncached(source, chunkPath).then(resolve);
chunkCache.set(chunkPath, entry);
}
// TODO: Return an instrumented Promise that React can use instead of relying on referential equality.
return entry === null ? loadedChunk : entry;
}
function loadChunkAsyncByUrl(source, chunkUrl) {
const path1 = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)); const path1 = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT));
return loadChunkAsync(source, path1); return loadChunkAsync(source, path1);
} }
...@@ -710,6 +724,9 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/; ...@@ -710,6 +724,9 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
*/ function isJs(chunkUrlOrPath) { */ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath); return regexJsUrl.test(chunkUrlOrPath);
} }
// For hot-reloader
;
globalThis.__turbopack_clear_chunk_cache__ = clearChunkCache;
module.exports = { module.exports = {
getOrInstantiateRuntimeModule, getOrInstantiateRuntimeModule,
loadChunk loadChunk
......
...@@ -482,28 +482,35 @@ async function loadChunk(source, chunkData) { ...@@ -482,28 +482,35 @@ async function loadChunk(source, chunkData) {
} }
return promise; return promise;
} }
async function loadChunkByUrl(source, chunkUrl) { const instrumentedBackendLoadChunks = new WeakMap();
try { // Do not make this async. React relies on referential equality of the returned Promise.
await BACKEND.loadChunk(chunkUrl, source); function loadChunkByUrl(source, chunkUrl) {
} catch (error) { const thenable = BACKEND.loadChunk(chunkUrl, source);
let loadReason; let entry = instrumentedBackendLoadChunks.get(thenable);
switch(source.type){ if (entry === undefined) {
case 0: entry = thenable.catch((error)=>{
loadReason = `as a runtime dependency of chunk ${source.chunkPath}`; let loadReason;
break; switch(source.type){
case 1: case 0:
loadReason = `from module ${source.parentId}`; loadReason = `as a runtime dependency of chunk ${source.chunkPath}`;
break; break;
case 2: case 1:
loadReason = 'from an HMR update'; loadReason = `from module ${source.parentId}`;
break; break;
default: case 2:
invariant(source, (source)=>`Unknown source type: ${source?.type}`); loadReason = 'from an HMR update';
} break;
throw new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${error ? `: ${error}` : ''}`, error ? { default:
cause: error invariant(source, (source)=>`Unknown source type: ${source?.type}`);
} : undefined); }
throw new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${error ? `: ${error}` : ''}`, error ? {
cause: error
} : undefined);
});
// TODO: Free the Promise once it resolves.
instrumentedBackendLoadChunks.set(thenable, entry);
} }
return entry;
} }
async function loadChunkPath(source, chunkPath) { async function loadChunkPath(source, chunkPath) {
const url = getChunkRelativeUrl(chunkPath); const url = getChunkRelativeUrl(chunkPath);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment