[Flight] use microtask for scheduling during prerenders (#30768)
In https://github.com/facebook/react/pull/29491 I updated the work scheduler for Flight to use microtasks to perform work when something pings. This is useful but it does have some downsides in terms of our ability to do task prioritization. Additionally the initial work is not instantiated using a microtask which is inconsistent with how pings work. In this change I update the scheduling logic to use microtasks consistently for prerenders and use regular tasks for renders both for the initial work and pings.
Josh Story committed
Aug 20, 2024 at 21:43 UTC
dc32c7f35ed6699e302dc7dbae17804555c669c6
4 files changed
+109
-13
packages/internal-test-utils/ReactInternalTestUtils.js
+1
-1
@@ -16,7 +16,7 @@ import {
16
clearErrors,
17
createLogAssertion,
18
} from './consoleMock';
19
-export {act} from './internalAct';
19
+export {act, serverAct} from './internalAct';
20
const {assertConsoleLogsCleared} = require('internal-test-utils/consoleMock');
21
22
import {thrownErrors, actingUpdatesScopeDepth} from './internalAct';
packages/internal-test-utils/internalAct.js
+87
@@ -192,3 +192,90 @@ export async function act<T>(scope: () => Thenable<T>): Thenable<T> {
192
}
193
}
194
}
195
+
196
+export async function serverAct<T>(scope: () => Thenable<T>): Thenable<T> {
197
+ // We require every `act` call to assert console logs
198
+ // with one of the assertion helpers. Fails if not empty.
199
+ assertConsoleLogsCleared();
200
+
201
+ // $FlowFixMe[cannot-resolve-name]: Flow doesn't know about global Jest object
202
+ if (!jest.isMockFunction(setTimeout)) {
203
+ throw Error(
204
+ "This version of `act` requires Jest's timer mocks " +
205
+ '(i.e. jest.useFakeTimers).',
206
+ );
207
+ }
208
+
209
+ // Create the error object before doing any async work, to get a better
210
+ // stack trace.
211
+ const error = new Error();
212
+ Error.captureStackTrace(error, act);
213
+
214
+ // Call the provided scope function after an async gap. This is an extra
215
+ // precaution to ensure that our tests do not accidentally rely on the act
216
+ // scope adding work to the queue synchronously. We don't do this in the
217
+ // public version of `act`, though we maybe should in the future.
218
+ await waitForMicrotasks();
219
+
220
+ const errorHandlerNode = function (err: mixed) {
221
+ thrownErrors.push(err);
222
+ };
223
+ // We track errors that were logged globally as if they occurred in this scope and then rethrow them.
224
+ if (typeof process === 'object') {
225
+ // Node environment
226
+ process.on('uncaughtException', errorHandlerNode);
227
+ } else if (
228
+ typeof window === 'object' &&
229
+ typeof window.addEventListener === 'function'
230
+ ) {
231
+ throw new Error('serverAct is not supported in JSDOM environments');
232
+ }
233
+
234
+ try {
235
+ const result = await scope();
236
+
237
+ do {
238
+ // Wait until end of current task/microtask.
239
+ await waitForMicrotasks();
240
+
241
+ // $FlowFixMe[cannot-resolve-name]: Flow doesn't know about global Jest object
242
+ if (jest.isEnvironmentTornDown()) {
243
+ error.message =
244
+ 'The Jest environment was torn down before `act` completed. This ' +
245
+ 'probably means you forgot to `await` an `act` call.';
246
+ throw error;
247
+ }
248
+
249
+ // $FlowFixMe[cannot-resolve-name]: Flow doesn't know about global Jest object
250
+ const j = jest;
251
+ if (j.getTimerCount() > 0) {
252
+ // There's a pending timer. Flush it now. We only do this in order to
253
+ // force Suspense fallbacks to display; the fact that it's a timer
254
+ // is an implementation detail. If there are other timers scheduled,
255
+ // those will also fire now, too, which is not ideal. (The public
256
+ // version of `act` doesn't do this.) For this reason, we should try
257
+ // to avoid using timers in our internal tests.
258
+ j.runOnlyPendingTimers();
259
+ // If a committing a fallback triggers another update, it might not
260
+ // get scheduled until a microtask. So wait one more time.
261
+ await waitForMicrotasks();
262
+ } else {
263
+ break;
264
+ }
265
+ } while (true);
266
+
267
+ if (thrownErrors.length > 0) {
268
+ // Rethrow any errors logged by the global error handling.
269
+ const thrownError = aggregateErrors(thrownErrors);
270
+ thrownErrors.length = 0;
271
+ throw thrownError;
272
+ }
273
+
274
+ return result;
275
+ } finally {
276
+ if (typeof process === 'object') {
277
+ // Node environment
278
+ process.off('uncaughtException', errorHandlerNode);
279
+ }
280
+ }
281
+}
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMEdge-test.js
+1
-8
@@ -23,10 +23,6 @@ if (typeof File === 'undefined' || typeof FormData === 'undefined') {
23
// Patch for Edge environments for global scope
24
global.AsyncLocalStorage = require('async_hooks').AsyncLocalStorage;
25
26
-const {
27
- patchMessageChannel,
28
-} = require('../../../../scripts/jest/patchMessageChannel');
29
-
26
let serverExports;
27
let clientExports;
28
let webpackMap;
@@ -39,7 +35,6 @@ let ReactServerDOMServer;
35
let ReactServerDOMStaticServer;
36
let ReactServerDOMClient;
37
let use;
42
-let ReactServerScheduler;
38
let reactServerAct;
39
40
function normalizeCodeLocInfo(str) {
@@ -55,9 +50,7 @@ describe('ReactFlightDOMEdge', () => {
50
beforeEach(() => {
51
jest.resetModules();
52
58
- ReactServerScheduler = require('scheduler');
59
- patchMessageChannel(ReactServerScheduler);
60
- reactServerAct = require('internal-test-utils').act;
53
+ reactServerAct = require('internal-test-utils').serverAct;
54
55
// Simulate the condition resolution
56
jest.mock('react', () => require('react/react.react-server'));
packages/react-server/src/ReactFlightServer.js
+20
-4
@@ -1794,7 +1794,11 @@ function pingTask(request: Request, task: Task): void {
1794
pingedTasks.push(task);
1795
if (pingedTasks.length === 1) {
1796
request.flushScheduled = request.destination !== null;
1797
- scheduleMicrotask(() => performWork(request));
1797
+ if (request.type === PRERENDER) {
1798
+ scheduleMicrotask(() => performWork(request));
1799
+ } else {
1800
+ scheduleWork(() => performWork(request));
1801
+ }
1802
}
1803
}
1804
@@ -4056,10 +4060,20 @@ function flushCompletedChunks(
4060
4061
export function startWork(request: Request): void {
4062
request.flushScheduled = request.destination !== null;
4059
- if (supportsRequestStorage) {
4060
- scheduleWork(() => requestStorage.run(request, performWork, request));
4063
+ if (request.type === PRERENDER) {
4064
+ if (supportsRequestStorage) {
4065
+ scheduleMicrotask(() => {
4066
+ requestStorage.run(request, performWork, request);
4067
+ });
4068
+ } else {
4069
+ scheduleMicrotask(() => performWork(request));
4070
+ }
4071
} else {
4062
- scheduleWork(() => performWork(request));
4072
+ if (supportsRequestStorage) {
4073
+ scheduleWork(() => requestStorage.run(request, performWork, request));
4074
+ } else {
4075
+ scheduleWork(() => performWork(request));
4076
+ }
4077
}
4078
}
4079
@@ -4073,6 +4087,8 @@ function enqueueFlush(request: Request): void {
4087
request.destination !== null
4088
) {
4089
request.flushScheduled = true;
4090
+ // Unlike startWork and pingTask we intetionally use scheduleWork
4091
+ // here even during prerenders to allow as much batching as possible
4092
scheduleWork(() => {
4093
request.flushScheduled = false;
4094
const destination = request.destination;