Skip to content

Commit

Permalink
Revert "use ALS for entire process object"
Browse files Browse the repository at this point in the history
This reverts commit 4be38fa.
  • Loading branch information
james-elicx committed Oct 23, 2024
1 parent 4628b62 commit 9ecefdf
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 42 deletions.
17 changes: 10 additions & 7 deletions packages/cloudflare/src/cli/templates/utils/create-als-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import type { AsyncLocalStorage } from "node:async_hooks";
*
* @param als AsyncLocalStorage instance
*/
export function createALSProxy<T extends object>(als: AsyncLocalStorage<T>) {
return new Proxy({} as T, {
ownKeys: () => Reflect.ownKeys(als.getStore()!),
getOwnPropertyDescriptor: (_, ...args) => Reflect.getOwnPropertyDescriptor(als.getStore()!, ...args),
get: (_, property) => Reflect.get(als.getStore()!, property),
set: (_, property, value) => Reflect.set(als.getStore()!, property, value),
});
export function createALSProxy<T>(als: AsyncLocalStorage<T>) {
return new Proxy(
{},
{
ownKeys: () => Reflect.ownKeys(als.getStore()!),
getOwnPropertyDescriptor: (_, ...args) => Reflect.getOwnPropertyDescriptor(als.getStore()!, ...args),
get: (_, property) => Reflect.get(als.getStore()!, property),
set: (_, property, value) => Reflect.set(als.getStore()!, property, value),
}
);
}
71 changes: 36 additions & 35 deletions packages/cloudflare/src/cli/templates/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,18 @@ import { createALSProxy } from "./utils";

const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);

const processALS = new AsyncLocalStorage<typeof process>();
const processEnvALS = new AsyncLocalStorage<Record<string, unknown>>();
const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();

// Note: this symbol needs to be kept in sync with the one defined in `src/api/get-cloudflare-context.ts`
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any)[Symbol.for("__cloudflare-context__")] = createALSProxy(cloudflareContextALS);

globalThis.process = createALSProxy(processALS);
globalThis.process = {
...globalThis.process,
// @ts-expect-error - populated when we run inside the ALS context
env: createALSProxy(processEnvALS),
};

// Injected at build time
const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
Expand All @@ -29,45 +33,42 @@ let requestHandler: NodeRequestHandler | null = null;

export default {
async fetch(request, env, ctx) {
return processALS.run(
{ ...globalThis.process, env: { ...globalThis.process.env, NODE_ENV: "production", ...env } },
() => {
return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
if (requestHandler == null) {
// Note: "next/dist/server/next-server" is a cjs module so we have to `require` it not to confuse esbuild
// (since esbuild can run in projects with different module resolutions)
// eslint-disable-next-line @typescript-eslint/no-require-imports
const NextNodeServer = require("next/dist/server/next-server")
.default as typeof import("next/dist/server/next-server").default;

requestHandler = new NextNodeServer({
conf: nextConfig,
customServer: false,
dev: false,
dir: "",
minimalMode: false,
}).getRequestHandler();
}
return processEnvALS.run({ NODE_ENV: "production", ...env }, () => {
return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
if (requestHandler == null) {
// Note: "next/dist/server/next-server" is a cjs module so we have to `require` it not to confuse esbuild
// (since esbuild can run in projects with different module resolutions)
// eslint-disable-next-line @typescript-eslint/no-require-imports
const NextNodeServer = require("next/dist/server/next-server")
.default as typeof import("next/dist/server/next-server").default;

requestHandler = new NextNodeServer({
conf: nextConfig,
customServer: false,
dev: false,
dir: "",
minimalMode: false,
}).getRequestHandler();
}

const url = new URL(request.url);
const url = new URL(request.url);

if (url.pathname === "/_next/image") {
const imageUrl =
url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
if (imageUrl.startsWith("/")) {
return env.ASSETS.fetch(new URL(imageUrl, request.url));
}
return fetch(imageUrl, { cf: { cacheEverything: true } });
if (url.pathname === "/_next/image") {
const imageUrl =
url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
if (imageUrl.startsWith("/")) {
return env.ASSETS.fetch(new URL(imageUrl, request.url));
}
return fetch(imageUrl, { cf: { cacheEverything: true } });
}

const { req, res, webResponse } = getWrappedStreams(request, ctx);
const { req, res, webResponse } = getWrappedStreams(request, ctx);

ctx.waitUntil(Promise.resolve(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res))));
ctx.waitUntil(Promise.resolve(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res))));

return await webResponse();
});
}
);
return await webResponse();
});
});
},
} as ExportedHandler<{ ASSETS: Fetcher }>;

Expand Down

0 comments on commit 9ecefdf

Please sign in to comment.