Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/ten-knives-tickle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen': patch
---

Workers context (e.g. `waitUntil`) is now scoped to the current request instead of globally available.
9 changes: 6 additions & 3 deletions packages/hydrogen/src/entry-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ import type {
} from './types';
import {Html, applyHtmlHead} from './framework/Hydration/Html';
import {ServerComponentResponse} from './framework/Hydration/ServerComponentResponse.server';
import {ServerComponentRequest} from './framework/Hydration/ServerComponentRequest.server';
import {
RuntimeContext,
ServerComponentRequest,
} from './framework/Hydration/ServerComponentRequest.server';
import {
preloadRequestCacheData,
ServerRequestProvider,
Expand All @@ -30,7 +33,7 @@ import {
} from './utilities/apiRoutes';
import {ServerPropsProvider} from './foundation/ServerPropsProvider';
import {isBotUA} from './utilities/bot-ua';
import {setContext, setCache, RuntimeContext} from './framework/runtime';
import {setCache} from './framework/runtime';
import {
ssrRenderToPipeableStream,
ssrRenderToReadableStream,
Expand Down Expand Up @@ -124,8 +127,8 @@ export const renderHydrogen = (App: any) => {
/**
* Inject the cache & context into the module loader so we can pull it out for subrequests.
*/
request.ctx.runtime = context;
setCache(cache);
setContext(context);

if (
url.pathname === EVENT_PATHNAME ||
Expand Down
57 changes: 33 additions & 24 deletions packages/hydrogen/src/foundation/useQuery/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
isStale,
setItemInCache,
} from '../../framework/cache-sub-request';
import {runDelayedFunction} from '../../framework/runtime';
import {useRequestCacheData, useServerRequest} from '../ServerRequestProvider';
import {CacheSeconds} from '../../framework/CachingStrategy';

Expand Down Expand Up @@ -111,29 +110,35 @@ function cachedQueryFnBuilder<T>(
if (isStale(key, response)) {
const lockKey = ['lock', ...(typeof key === 'string' ? [key] : key)];

runDelayedFunction(async () => {
const lockExists = await getItemFromCache(lockKey);
if (lockExists) return;

await setItemInCache(
lockKey,
true,
CacheSeconds({
maxAge: 10,
})
);
try {
const output = await generateNewOutput();

if (shouldCacheResponse(output)) {
await setItemInCache(key, output, resolvedQueryOptions?.cache);
// Run revalidation asynchronously
const revalidatingPromise = getItemFromCache(lockKey).then(
async (lockExists) => {
if (lockExists) return;

await setItemInCache(
lockKey,
true,
CacheSeconds({
maxAge: 10,
})
);

try {
const output = await generateNewOutput();

if (shouldCacheResponse(output)) {
await setItemInCache(key, output, resolvedQueryOptions?.cache);
}
} catch (e: any) {
log.error(`Error generating async response: ${e.message}`);
} finally {
await deleteItemFromCache(lockKey);
}
} catch (e: any) {
log.error(`Error generating async response: ${e.message}`);
} finally {
await deleteItemFromCache(lockKey);
}
});
);

// Asynchronously wait for it in workers
request.ctx.runtime?.waitUntil?.(revalidatingPromise);
}

return output;
Expand All @@ -145,9 +150,13 @@ function cachedQueryFnBuilder<T>(
* Important: Do this async
*/
if (shouldCacheResponse(newOutput)) {
runDelayedFunction(() =>
setItemInCache(key, newOutput, resolvedQueryOptions?.cache)
const setItemInCachePromise = setItemInCache(
key,
newOutput,
resolvedQueryOptions?.cache
);

request.ctx.runtime?.waitUntil?.(setItemInCachePromise);
}

collectQueryCacheControlHeaders(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import {RSC_PATHNAME} from '../../constants';
import {SessionSyncApi} from '../../foundation/session/session';
import {parseJSON} from '../../utilities/parse';

export interface RuntimeContext {
waitUntil: (fn: Promise<any>) => void;
}

export type PreloadQueryEntry = {
key: QueryKey;
fetcher: () => Promise<unknown>;
Expand Down Expand Up @@ -64,6 +68,7 @@ export class ServerComponentRequest extends Request {
router: RouterContextData;
buyerIpHeader?: string;
session?: SessionSyncApi;
runtime?: RuntimeContext;
[key: string]: any;
};

Expand Down
31 changes: 0 additions & 31 deletions packages/hydrogen/src/framework/runtime.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,11 @@
declare namespace globalThis {
let __ctx: RuntimeContext | undefined;
let __cache: Cache | undefined;
}

export interface RuntimeContext {
waitUntil: (fn: Promise<any>) => void;
}

/**
* Set a global runtime context for the current request.
* This is used to encapsulate things like:
* - `waitUntil()` to run promises after request has ended
*/
export function setContext(ctx?: RuntimeContext) {
globalThis.__ctx = ctx;
}

export function getContext() {
return globalThis.__ctx;
}

export function setCache(cache?: Cache) {
globalThis.__cache = cache;
}

export function getCache(): Cache | undefined {
return globalThis.__cache;
}

export function runDelayedFunction(fn: () => Promise<any>) {
const context = getContext();

/**
* Runtimes (Oxygen, Node.js) might not have this.
*/
if (!context?.waitUntil) {
return fn();
}

return context.waitUntil(fn());
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {useShopQuery} from '../hooks';
import {mountWithProviders} from '../../../utilities/tests/shopifyMount';
import {ServerRequestProvider} from '../../../foundation/ServerRequestProvider';
import {ServerComponentRequest} from '../../../framework/Hydration/ServerComponentRequest.server';
import {setCache, setContext} from '../../../framework/runtime';
import {setCache} from '../../../framework/runtime';
import {InMemoryCache} from '../../../framework/cache/in-memory';

jest.mock('../../../foundation/ssr-interop', () => {
Expand All @@ -13,6 +13,8 @@ jest.mock('../../../foundation/ssr-interop', () => {
};
});

let waitUntilPromises = [] as Array<Promise<any>>;

function mountComponent() {
function Component() {
const result = useShopQuery({query: 'query { test {} }'});
Expand All @@ -23,6 +25,10 @@ function mountComponent() {
new Request('https://example.com')
);

request.ctx.runtime = {
waitUntil: (p: Promise<any>) => waitUntilPromises.push(p),
};

return mountWithProviders(
<ServerRequestProvider request={request} isRSC={true}>
<Suspense fallback={null}>
Expand All @@ -35,7 +41,6 @@ function mountComponent() {
describe('useShopQuery', () => {
const originalFetch = globalThis.fetch;
const mockedFetch = jest.fn(originalFetch);
let waitUntilPromises: Array<Promise<any>>;
let cache: Cache;
let consoleErrorSpy: jest.SpyInstance;

Expand All @@ -45,7 +50,6 @@ describe('useShopQuery', () => {

beforeEach(() => {
waitUntilPromises = [];
setContext({waitUntil: (p: Promise<any>) => waitUntilPromises.push(p)});
cache = new InMemoryCache() as unknown as Cache;
setCache(cache);
consoleErrorSpy = jest.spyOn(console, 'error');
Expand All @@ -58,7 +62,6 @@ describe('useShopQuery', () => {

afterAll(() => {
globalThis.fetch = originalFetch;
setContext(undefined);
setCache(undefined);
});

Expand Down