Skip to content

Commit 8baaa31

Browse files
authored
Merge pull request #5405 from cloudflare/jasnell/shared-fetcher-on-request
2 parents 47c9b94 + 73d4f5f commit 8baaa31

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/workerd/api/global-scope.c++

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,8 +218,18 @@ kj::Promise<DeferredProxy<void>> ServiceWorkerGlobalScope::request(kj::HttpMetho
218218
}
219219
}
220220

221+
if (defaultFetcher == kj::none) {
222+
// The default fetcher can be shared across requests since it does not persist any
223+
// request-specific state. We can create one lazily here for the first request
224+
// handled by this global scope and avoid the extra allocations on subsequence requests.
225+
// We could also consider creating it lazily when first accessed, but Fetcher is very
226+
// lightweight so this seems sufficient for now.
227+
defaultFetcher =
228+
js.alloc<Fetcher>(IoContext::NEXT_CLIENT_CHANNEL, Fetcher::RequiresHostAndProtocol::YES);
229+
}
230+
221231
auto jsRequest = js.alloc<Request>(js, method, url, Request::Redirect::MANUAL, kj::mv(jsHeaders),
222-
js.alloc<Fetcher>(IoContext::NEXT_CLIENT_CHANNEL, Fetcher::RequiresHostAndProtocol::YES),
232+
KJ_ASSERT_NONNULL(defaultFetcher).addRef(),
223233
/* signal */ kj::mv(abortSignal), kj::mv(cf), kj::mv(body),
224234
/* thisSignal */ kj::none, Request::CacheMode::NONE);
225235

src/workerd/api/global-scope.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,7 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope {
930930
jsg::UnhandledRejectionHandler unhandledRejections;
931931
kj::Maybe<jsg::JsRef<jsg::JsValue>> processValue;
932932
kj::Maybe<jsg::JsRef<jsg::JsValue>> bufferValue;
933+
kj::Maybe<jsg::Ref<Fetcher>> defaultFetcher;
933934

934935
// Global properties such as scheduler, crypto, caches, self, and origin should
935936
// be monkeypatchable / mutable at the global scope.

0 commit comments

Comments
 (0)