From a90210e3ba0751cf1d47f44dee07d01d49744234 Mon Sep 17 00:00:00 2001 From: Chris Dickinson Date: Wed, 14 May 2025 12:30:51 -0700 Subject: [PATCH] fix(jspi): JSPI should not override http calls in worker context This fixes a bug where we'd use the system `fetch` inside a plugin run in a worker when JSPI was enabled, bypassing overrides of the `fetch` function. --- src/foreground-plugin.ts | 8 ++++++-- src/interfaces.ts | 1 + src/mod.ts | 1 + src/worker.ts | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/foreground-plugin.ts b/src/foreground-plugin.ts index 585d3aa..bc07e51 100644 --- a/src/foreground-plugin.ts +++ b/src/foreground-plugin.ts @@ -244,13 +244,17 @@ async function instantiateModule( // haven't overridden the default CallContext implementation, we provide an HttpContext // on-demand. // - // Unfortuantely this duplicates a little bit of logic-- in particular, we have to bind + // Unfortunately this duplicates a little bit of logic-- in particular, we have to bind // CallContext to each of the HttpContext contributions (See "REBIND" below.) + // + // Notably, if we're calling this from a background thread, skip all of the patching: + // we want to dispatch to the main thread. if ( module === EXTISM_ENV && name === 'http_request' && promising && - imports[module][name] === context[ENV].http_request + imports[module][name] === context[ENV].http_request && + !opts.executingInWorker ) { const httpContext = new HttpContext(opts.fetch, opts.allowedHosts, opts.memory, opts.allowHttpResponseHeaders); diff --git a/src/interfaces.ts b/src/interfaces.ts index d852b33..ece36f8 100644 --- a/src/interfaces.ts +++ b/src/interfaces.ts @@ -287,6 +287,7 @@ export interface InternalConfig extends Required { sharedArrayBufferSize: number; allowHttpResponseHeaders: boolean; nodeWorkerArgs: NodeWorkerArgs; + executingInWorker: boolean; } export interface InternalWasi { diff --git a/src/mod.ts b/src/mod.ts index 6fd91f7..b47ee08 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -136,6 +136,7 @@ export async function createPlugin( } const ic: InternalConfig = { + executingInWorker: false, allowedHosts: opts.allowedHosts as [], allowedPaths: opts.allowedPaths, functions: opts.functions, diff --git a/src/worker.ts b/src/worker.ts index d57d71f..47030c0 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -155,7 +155,7 @@ class Reactor { // TODO: replace our internal fetch and logger this.plugin = await _createForegroundPlugin( - { ...opts, functions, fetch, logger } as InternalConfig, + { ...opts, functions, fetch, logger, executingInWorker: true } as InternalConfig, ev.names, modules, this.context,