From db586ec8d17be380b3dfbe5607f6ec58c2ede235 Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Sat, 22 Oct 2022 22:58:57 -0400 Subject: [PATCH] Cache --- packages/react-server/src/ReactFlightServer.js | 15 ++++++++++++--- .../src/ReactFlightServerConfigStream.js | 5 +++++ .../src/ReactServerStreamConfigBrowser.js | 5 +++++ .../src/ReactServerStreamConfigNode.js | 4 ++++ packages/react/src/__tests__/ReactFetch-test.js | 16 ++++++++++++++++ scripts/error-codes/codes.json | 3 ++- scripts/rollup/bundles.js | 4 ++-- 7 files changed, 46 insertions(+), 6 deletions(-) diff --git a/packages/react-server/src/ReactFlightServer.js b/packages/react-server/src/ReactFlightServer.js index ff19ea3abc839..5e4232a6cd984 100644 --- a/packages/react-server/src/ReactFlightServer.js +++ b/packages/react-server/src/ReactFlightServer.js @@ -43,6 +43,8 @@ import { resolveModuleMetaData, getModuleKey, isModuleReference, + supportsRequestStorage, + requestStorage, } from './ReactFlightServerConfig'; import { @@ -157,6 +159,16 @@ export function createRequest( context?: Array<[string, ServerContextJSONValue]>, identifierPrefix?: string, ): Request { + if ( + ReactCurrentCache.current !== null && + ReactCurrentCache.current !== DefaultCacheDispatcher + ) { + throw new Error( + 'Currently React only supports one RSC renderer at a time.', + ); + } + ReactCurrentCache.current = DefaultCacheDispatcher; + const abortSet: Set = new Set(); const pingedTasks = []; const request = { @@ -1155,10 +1167,8 @@ function retryTask(request: Request, task: Task): void { function performWork(request: Request): void { const prevDispatcher = ReactCurrentDispatcher.current; - const prevCacheDispatcher = ReactCurrentCache.current; const prevCache = getCurrentCache(); ReactCurrentDispatcher.current = HooksDispatcher; - ReactCurrentCache.current = DefaultCacheDispatcher; setCurrentCache(request.cache); prepareToUseHooksForRequest(request); @@ -1177,7 +1187,6 @@ function performWork(request: Request): void { fatalError(request, error); } finally { ReactCurrentDispatcher.current = prevDispatcher; - ReactCurrentCache.current = prevCacheDispatcher; setCurrentCache(prevCache); resetHooksForRequest(); } diff --git a/packages/react-server/src/ReactFlightServerConfigStream.js b/packages/react-server/src/ReactFlightServerConfigStream.js index 063f5323bbfa9..d5e4ec6f6371a 100644 --- a/packages/react-server/src/ReactFlightServerConfigStream.js +++ b/packages/react-server/src/ReactFlightServerConfigStream.js @@ -72,6 +72,11 @@ import type {Chunk} from './ReactServerStreamConfig'; export type {Destination, Chunk} from './ReactServerStreamConfig'; +export { + supportsRequestStorage, + requestStorage, +} from './ReactServerStreamConfig'; + const stringify = JSON.stringify; function serializeRowHeader(tag: string, id: number) { diff --git a/packages/react-server/src/ReactServerStreamConfigBrowser.js b/packages/react-server/src/ReactServerStreamConfigBrowser.js index f48273bbadfac..dd7108a6752a2 100644 --- a/packages/react-server/src/ReactServerStreamConfigBrowser.js +++ b/packages/react-server/src/ReactServerStreamConfigBrowser.js @@ -21,6 +21,11 @@ export function flushBuffered(destination: Destination) { // transform streams. https://github.com/whatwg/streams/issues/960 } +// For now we support AsyncLocalStorage as a global for the "browser" builds +// TODO: Move this to some special WinterCG build. +export const supportsRequestStorage = typeof AsyncLocalStorage === 'function'; +export const requestStorage = new AsyncLocalStorage(); + const VIEW_SIZE = 512; let currentView = null; let writtenBytes = 0; diff --git a/packages/react-server/src/ReactServerStreamConfigNode.js b/packages/react-server/src/ReactServerStreamConfigNode.js index 282dd193182b3..9ebfe7f7a41e6 100644 --- a/packages/react-server/src/ReactServerStreamConfigNode.js +++ b/packages/react-server/src/ReactServerStreamConfigNode.js @@ -9,6 +9,7 @@ import type {Writable} from 'stream'; import {TextEncoder} from 'util'; +import {AsyncLocalStorage} from 'async_hooks'; interface MightBeFlushable { flush?: () => void; @@ -33,6 +34,9 @@ export function flushBuffered(destination: Destination) { } } +export const supportsRequestStorage = true; +export const requestStorage = new AsyncLocalStorage(); + const VIEW_SIZE = 2048; let currentView = null; let writtenBytes = 0; diff --git a/packages/react/src/__tests__/ReactFetch-test.js b/packages/react/src/__tests__/ReactFetch-test.js index 6d25a9ddd05a6..c86748432030a 100644 --- a/packages/react/src/__tests__/ReactFetch-test.js +++ b/packages/react/src/__tests__/ReactFetch-test.js @@ -76,6 +76,22 @@ describe('ReactFetch', () => { expect(fetchCount).toBe(1); }); + // @gate enableFetchInstrumentation && enableCache + it('can dedupe fetches in micro tasks', async () => { + async function getData() { + const r1 = await fetch('hello'); + const t1 = await r1.text(); + const r2 = await fetch('hello'); + const t2 = await r2.text(); + return t1 + ' ' + t2; + } + function Component() { + return use(getData()); + } + expect(await render(Component)).toMatchInlineSnapshot(`"GET world []"`); + expect(fetchCount).toBe(2); + }); + // @gate enableFetchInstrumentation && enableCache it('can dedupe fetches using Request and not', async () => { function Component() { diff --git a/scripts/error-codes/codes.json b/scripts/error-codes/codes.json index e35b9547f2fb6..412b53791cd60 100644 --- a/scripts/error-codes/codes.json +++ b/scripts/error-codes/codes.json @@ -442,5 +442,6 @@ "454": "React expected a element (document.body) to exist in the Document but one was not found. React never removes the body for any Document it renders into so the cause is likely in some other script running on this page.", "455": "This CacheSignal was requested outside React which means that it is immediately aborted.", "456": "Calling Offscreen.detach before instance handle has been set.", - "457": "acquireHeadResource encountered a resource type it did not expect: \"%s\". This is a bug in React." + "457": "acquireHeadResource encountered a resource type it did not expect: \"%s\". This is a bug in React.", + "458": "Currently React only supports one RSC renderer at a time" } diff --git a/scripts/rollup/bundles.js b/scripts/rollup/bundles.js index 36a9627799fc5..deba31cbf1232 100644 --- a/scripts/rollup/bundles.js +++ b/scripts/rollup/bundles.js @@ -320,7 +320,7 @@ const bundles = [ global: 'ReactDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, - externals: ['react', 'util', 'react-dom'], + externals: ['react', 'util', 'async-hooks', 'react-dom'], }, { bundleTypes: __EXPERIMENTAL__ ? [FB_WWW_DEV, FB_WWW_PROD] : [], @@ -394,7 +394,7 @@ const bundles = [ global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, - externals: ['react', 'util', 'react-dom'], + externals: ['react', 'util', 'async-hooks', 'react-dom'], }, /******* React Server DOM Webpack Client *******/