Commit 3fd2cd00 authored by Tobias Koppers's avatar Tobias Koppers

Fix SharedWorker initialization race and address review feedback

- Make ESM evaluate chunk IIFE async and await `BACKEND.registerChunk()` so
  `import(evaluate_chunk)` only resolves after all modules are instantiated.
  Without this, SharedWorkers fire the `connect` event before `onconnect`
  listeners are registered.
- Rename `worker_chunk_context(is_esm)` → `esm_chunking_context()` (no param).
  Callers only call it when `is_esm` is true; the impl returns `self` when
  `esm_chunks` is already set (fixes the comparison-vs-self.esm_chunks concern).
- Remove redundant `chunkUrls.reverse()` from ESM worker bootstrap; `import()`
  loads in parallel so order doesn't matter.
- Deduplicate preinit loop in `required-scripts.tsx` using a `preinitFn`
  variable instead of duplicating the loop body.
- Remove debug logging from shared worker test.
- Fix comment wording: "not yet an array" → "not an array".
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 6adf1869
...@@ -56,6 +56,7 @@ export function getRequiredScripts( ...@@ -56,6 +56,7 @@ export function getRequiredScripts(
'Invariant: missing bootstrap script. This is a bug in Next.js' 'Invariant: missing bootstrap script. This is a bug in Next.js'
) )
} }
const preinitFn = isEsmChunks ? ReactDOM.preinitModule : ReactDOM.preinit
if (SRIManifest) { if (SRIManifest) {
bootstrapScript.src = `${assetPrefix}/_next/` + files[0] + qs bootstrapScript.src = `${assetPrefix}/_next/` + files[0] + qs
bootstrapScript.integrity = SRIManifest[files[0]] bootstrapScript.integrity = SRIManifest[files[0]]
...@@ -65,29 +66,15 @@ export function getRequiredScripts( ...@@ -65,29 +66,15 @@ export function getRequiredScripts(
const integrity = SRIManifest[files[i]] const integrity = SRIManifest[files[i]]
preinitScriptCommands.push(src, integrity) preinitScriptCommands.push(src, integrity)
} }
if (isEsmChunks) { preinitScripts = () => {
preinitScripts = () => { // preinitScriptCommands is a double indexed array of src/integrity pairs
// preinitScriptCommands is a double indexed array of src/integrity pairs for (let i = 0; i < preinitScriptCommands.length; i += 2) {
for (let i = 0; i < preinitScriptCommands.length; i += 2) { preinitFn(preinitScriptCommands[i], {
ReactDOM.preinitModule(preinitScriptCommands[i], { as: 'script',
as: 'script', integrity: preinitScriptCommands[i + 1],
integrity: preinitScriptCommands[i + 1], crossOrigin,
crossOrigin, nonce,
nonce, })
})
}
}
} else {
preinitScripts = () => {
// preinitScriptCommands is a double indexed array of src/integrity pairs
for (let i = 0; i < preinitScriptCommands.length; i += 2) {
ReactDOM.preinit(preinitScriptCommands[i], {
as: 'script',
integrity: preinitScriptCommands[i + 1],
crossOrigin,
nonce,
})
}
} }
} }
} else { } else {
...@@ -97,27 +84,14 @@ export function getRequiredScripts( ...@@ -97,27 +84,14 @@ export function getRequiredScripts(
const src = `${assetPrefix}/_next/` + files[i] + qs const src = `${assetPrefix}/_next/` + files[i] + qs
preinitScriptCommands.push(src) preinitScriptCommands.push(src)
} }
if (isEsmChunks) { preinitScripts = () => {
preinitScripts = () => { // preinitScriptCommands is a singled indexed array of src values
// preinitScriptCommands is a singled indexed array of src values for (let i = 0; i < preinitScriptCommands.length; i++) {
for (let i = 0; i < preinitScriptCommands.length; i++) { preinitFn(preinitScriptCommands[i], {
ReactDOM.preinitModule(preinitScriptCommands[i], { as: 'script',
as: 'script', nonce,
nonce, crossOrigin,
crossOrigin, })
})
}
}
} else {
preinitScripts = () => {
// preinitScriptCommands is a singled indexed array of src values
for (let i = 0; i < preinitScriptCommands.length; i++) {
ReactDOM.preinit(preinitScriptCommands[i], {
as: 'script',
nonce,
crossOrigin,
})
}
} }
} }
} }
......
...@@ -128,12 +128,9 @@ describe('app dir - workers', () => { ...@@ -128,12 +128,9 @@ describe('app dir - workers', () => {
await browser.elementByCss('button').click() await browser.elementByCss('button').click()
await retry(async () => { await retry(async () => {
const text = await browser.elementByCss('#worker-state').text() expect(await browser.elementByCss('#worker-state').text()).toBe(
// Log the state for debugging CI failures 'shared-worker.ts:worker-dep:2'
if (text !== 'default' && text !== 'shared-worker.ts:worker-dep:2') { )
console.log('Unexpected worker state:', text)
}
expect(text).toBe('shared-worker.ts:worker-dep:2')
}) })
}) })
......
...@@ -985,11 +985,8 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -985,11 +985,8 @@ impl ChunkingContext for BrowserChunkingContext {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn worker_chunk_context( async fn esm_chunking_context(self: Vc<Self>) -> Result<Vc<Box<dyn ChunkingContext>>> {
self: Vc<Self>, if self.await?.esm_chunks {
is_esm: bool,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
if !is_esm {
return Ok(Vc::upcast(self)); return Ok(Vc::upcast(self));
} }
let mut inner = (*self.await?).clone(); let mut inner = (*self.await?).clone();
......
...@@ -267,10 +267,6 @@ fn generate_module_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result< ...@@ -267,10 +267,6 @@ fn generate_module_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result<
{globals} {globals}
}}); }});
// Restore original chunk order (params are stored reversed) so that
// TURBOPACK_NEXT_CHUNK_URLS matches the original order.
chunkUrls.reverse();
await Promise.all(chunkUrls.map(function(chunk) {{ await Promise.all(chunkUrls.map(function(chunk) {{
var chunkUrl = new URL(chunk, location.origin); var chunkUrl = new URL(chunk, location.origin);
if (chunkUrl.origin !== location.origin) {{ if (chunkUrl.origin !== location.origin) {{
......
...@@ -495,18 +495,15 @@ pub trait ChunkingContext { ...@@ -495,18 +495,15 @@ pub trait ChunkingContext {
turbobail!("Worker entrypoint is not supported by {}", self.name()); turbobail!("Worker entrypoint is not supported by {}", self.name());
} }
/// Returns a derived chunking context suitable for building a worker's chunk group. /// Returns a derived chunking context that always emits ESM chunks.
/// ///
/// When `is_esm` is true the returned context must emit ESM chunks (using `import()` /// Used when building a module worker's chunk group: ESM chunks use `import()`
/// for chunk loading) so that the worker runtime can load dependencies without /// for chunk loading instead of `importScripts`, which is forbidden in module workers.
/// calling `importScripts`, which is forbidden in module workers. /// Returns `self` if the context already emits ESM chunks.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn worker_chunk_context( async fn esm_chunking_context(self: Vc<Self>) -> Result<Vc<Box<dyn ChunkingContext>>> {
self: Vc<Self>,
_is_esm: bool,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
turbobail!( turbobail!(
"worker_chunk_context is not implemented for {}", "esm_chunking_context is not implemented for {}",
self.name() self.name()
) )
} }
......
...@@ -98,7 +98,24 @@ pub async fn get_browser_runtime_code( ...@@ -98,7 +98,24 @@ pub async fn get_browser_runtime_code(
let chunk_loading_global = chunk_loading_global.await?; let chunk_loading_global = chunk_loading_global.await?;
let chunk_lists_global = format!("{}_CHUNK_LISTS", &*chunk_loading_global); let chunk_lists_global = format!("{}_CHUNK_LISTS", &*chunk_loading_global);
if *environment if esm_chunks {
// In ESM mode the evaluate chunk is itself an ES module, so top-level `await` is
// available. We make the IIFE async and await it at the module level so that
// `import(evaluate_chunk)` only resolves after `registerChunk` (and all its async
// sub-tasks — loading other chunks, instantiating runtime modules) has completed.
// This is required for SharedWorkers where the `connect` event fires right after the
// module's top-level execution is done; without the await, `shared-worker.ts`'s
// `addEventListener('connect', ...)` would not yet have been registered.
if *environment
.runtime_versions()
.supports_arrow_functions()
.await?
{
code += "await (async () => {\n";
} else {
code += "await (async function(){\n";
}
} else if *environment
.runtime_versions() .runtime_versions()
.supports_arrow_functions() .supports_arrow_functions()
.await? .await?
...@@ -109,7 +126,7 @@ pub async fn get_browser_runtime_code( ...@@ -109,7 +126,7 @@ pub async fn get_browser_runtime_code(
} }
if !esm_chunks { if !esm_chunks {
// In classic script mode the IIFE bails out if TURBOPACK is not yet an array // In classic script mode the IIFE bails out if TURBOPACK is not an array
// (i.e., a second evaluate chunk ran before the first finished bootstrapping). // (i.e., a second evaluate chunk ran before the first finished bootstrapping).
writedoc!( writedoc!(
code, code,
...@@ -254,10 +271,12 @@ pub async fn get_browser_runtime_code( ...@@ -254,10 +271,12 @@ pub async fn get_browser_runtime_code(
// ESM mode: the RuntimeParams are in __turbopack_params__ (a const defined before // ESM mode: the RuntimeParams are in __turbopack_params__ (a const defined before
// the runtime IIFE in the same evaluate chunk file). No TURBOPACK global to drain. // the runtime IIFE in the same evaluate chunk file). No TURBOPACK global to drain.
// Pass an empty string as the chunk path — the ESM registerChunk ignores it. // Pass an empty string as the chunk path — the ESM registerChunk ignores it.
// We await here (inside the async IIFE) so the module-level `await` at the top
// propagates all the way through chunk loading and module instantiation.
writedoc!( writedoc!(
code, code,
r#" r#"
BACKEND.registerChunk("", __turbopack_params__); await BACKEND.registerChunk("", __turbopack_params__);
"#, "#,
)?; )?;
} else { } else {
......
...@@ -68,7 +68,11 @@ impl WorkerLoaderModule { ...@@ -68,7 +68,11 @@ impl WorkerLoaderModule {
// When `is_esm` is true, use a derived context that emits ESM chunks so the // When `is_esm` is true, use a derived context that emits ESM chunks so the
// worker runtime can load dependencies via `import()` instead of // worker runtime can load dependencies via `import()` instead of
// `importScripts` (which is forbidden in module workers). // `importScripts` (which is forbidden in module workers).
let worker_context = chunking_context.worker_chunk_context(this.is_esm); let worker_context = if this.is_esm {
chunking_context.esm_chunking_context()
} else {
chunking_context
};
worker_context.evaluated_chunk_group_assets( worker_context.evaluated_chunk_group_assets(
this.inner this.inner
.ident() .ident()
......
...@@ -737,10 +737,7 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -737,10 +737,7 @@ impl ChunkingContext for NodeJsChunkingContext {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn worker_chunk_context( async fn esm_chunking_context(self: Vc<Self>) -> Result<Vc<Box<dyn ChunkingContext>>> {
self: Vc<Self>,
_is_esm: bool,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
Ok(Vc::upcast(self)) Ok(Vc::upcast(self))
} }
} }
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