Commit f4bf0963 authored by Tobias Koppers's avatar Tobias Koppers

Buffer connect events in ESM worker bootstrap to fix SharedWorker race

The async `await Promise.all(...)` in the ESM bootstrap creates a task
checkpoint where the browser event loop can dispatch `connect` events
before the user module has registered its `addEventListener('connect', ...)`
handler. For SharedWorkers, this causes the connect event to be silently
dropped.

Fix by buffering connect events synchronously before the await, then
replaying them after initialization completes. The SharedWorkerGlobalScope
check is runtime-only so regular Workers are unaffected.

Also removes the unnecessary foreign-origin check in the import map callback
(the chunks are always same-origin, and import() enforces CORS itself).
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent be519dc4
...@@ -253,6 +253,10 @@ fn generate_script_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result< ...@@ -253,6 +253,10 @@ fn generate_script_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result<
/// Uses dynamic `import()` to load chunks in parallel. Because the entrypoint file itself is /// Uses dynamic `import()` to load chunks in parallel. Because the entrypoint file itself is
/// served with `type: "module"`, top-level `await` is available and all loaded chunks run in /// served with `type: "module"`, top-level `await` is available and all loaded chunks run in
/// strict mode. /// strict mode.
///
/// For SharedWorkers, the `await Promise.all(...)` creates a suspension point where the browser
/// event loop can dispatch `connect` events before the user module has registered its listener.
/// To fix this, connect events are buffered before the `await` and replayed after.
fn generate_module_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result<Code> { fn generate_module_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result<Code> {
let mut code: CodeBuilder = CodeBuilder::default(); let mut code: CodeBuilder = CodeBuilder::default();
let preamble = build_preamble_js(); let preamble = build_preamble_js();
...@@ -267,13 +271,28 @@ fn generate_module_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result< ...@@ -267,13 +271,28 @@ fn generate_module_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result<
{globals} {globals}
}}); }});
// Buffer connect events for SharedWorkers: the async await below creates a suspension
// point where the browser can dispatch connect before the user module has registered
// its addEventListener('connect', ...) handler.
var _connectBuffer_ = null;
var _connectListener_ = null;
if (typeof self['SharedWorkerGlobalScope'] !== 'undefined' && self instanceof self['SharedWorkerGlobalScope']) {{
_connectBuffer_ = [];
_connectListener_ = function(e) {{ _connectBuffer_.push(e.ports[0]); }};
self.addEventListener('connect', _connectListener_);
}}
await Promise.all(chunkUrls.map(function(chunk) {{ await Promise.all(chunkUrls.map(function(chunk) {{
var chunkUrl = new URL(chunk, location.origin); return import(chunk);
if (chunkUrl.origin !== location.origin) {{
abort("Refusing to load script from foreign origin: " + chunkUrl.origin);
}}
return import(chunkUrl.toString());
}})); }}));
// Replay connect events that arrived during async initialization
if (_connectBuffer_ !== null) {{
self.removeEventListener('connect', _connectListener_);
for (var _i_ = 0; _i_ < _connectBuffer_.length; _i_++) {{
self.dispatchEvent(new MessageEvent('connect', {{ ports: [_connectBuffer_[_i_]] }}));
}}
}}
"##, "##,
preamble = preamble, preamble = preamble,
globals = globals globals = globals
......
...@@ -27,10 +27,25 @@ Object.assign(self, { ...@@ -27,10 +27,25 @@ Object.assign(self, {
TURBOPACK_ASSET_SUFFIX: param(1) TURBOPACK_ASSET_SUFFIX: param(1)
}); });
// Buffer connect events for SharedWorkers: the async await below creates a suspension
// point where the browser can dispatch connect before the user module has registered
// its addEventListener('connect', ...) handler.
var _connectBuffer_ = null;
var _connectListener_ = null;
if (typeof self['SharedWorkerGlobalScope'] !== 'undefined' && self instanceof self['SharedWorkerGlobalScope']) {
_connectBuffer_ = [];
_connectListener_ = function(e) { _connectBuffer_.push(e.ports[0]); };
self.addEventListener('connect', _connectListener_);
}
await Promise.all(chunkUrls.map(function(chunk) { await Promise.all(chunkUrls.map(function(chunk) {
var chunkUrl = new URL(chunk, location.origin); return import(chunk);
if (chunkUrl.origin !== location.origin) { }));
abort("Refusing to load script from foreign origin: " + chunkUrl.origin);
// Replay connect events that arrived during async initialization
if (_connectBuffer_ !== null) {
self.removeEventListener('connect', _connectListener_);
for (var _i_ = 0; _i_ < _connectBuffer_.length; _i_++) {
self.dispatchEvent(new MessageEvent('connect', { ports: [_connectBuffer_[_i_]] }));
} }
return import(chunkUrl.toString()); }
})); \ No newline at end of file
\ No newline at end of file
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