Skip to content

Commit

Permalink
[Flight] Instrument the Console in the RSC Environment and Replay Log…
Browse files Browse the repository at this point in the history
…s on the Client (facebook#28384)

When developing in an RSC environment, you should be able to work in a
single environment as if it was a unified environment. With thrown
errors we already serialize them and then rethrow them on the client.

Since by default we log them via onError both in Flight and Fizz, you
can get the same log in the RSC runtime, the SSR runtime and on the
client.

With console logs made in SSR renders, you typically replay the same
code during hydration on the client. So for example warnings already
show up both in the SSR logs and on the client (although not guaranteed
to be the same). You could just spend your time in the client and you'd
be fine.

Previously, RSC logs would not be replayed because they don't hydrate.
So it's easy to miss warnings for example.

With this approach, we replay RSC logs both during SSR so they end up in
the SSR logs and on the client. That way you can just stay in the
browser window during normal development cycles. You shouldn't have to
care if your component is a server or client component when working on
logical things or iterating on a product.

With this change, you probably should mostly ignore the Flight log
stream and just look at the client or maybe the SSR one. Unless you're
digging into something specific. In particular if you just naively run
both Flight and Fizz in the same terminal you get duplicates. I like to
run out fixtures `yarn dev:region` and `yarn dev:global` in two separate
terminals.

Console logs may contain complex objects which can be inspected. Ideally
a DevTools inspector could reach into the RSC server and remotely
inspect objects using the remote inspection protocol. That way complex
objects can be loaded on demand as you expand into them. However, that
is a complex environment to set up and the server might not even be
alive anymore by the time you inspect the objects. Therefore, I do a
best effort to serialize the objects using the RSC protocol but limit
the depth that can be rendered.

This feature is only own in dev mode since it can be expensive.

In a follow up, I'll give the logs a special styling treatment to
clearly differentiate them from logs coming from the client. As well as
deal with stacks.
  • Loading branch information
sebmarkbage authored and AndyPengc12 committed Apr 15, 2024
1 parent 2e05076 commit 19c3266
Show file tree
Hide file tree
Showing 30 changed files with 567 additions and 33 deletions.
47 changes: 47 additions & 0 deletions packages/react-client/src/ReactFlightClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,10 @@ function parseModelString(
}
case '@': {
// Promise
if (value.length === 2) {
// Infinite promise that never resolves.
return new Promise(() => {});
}
const id = parseInt(value.slice(2), 16);
const chunk = getChunk(response, id);
return chunk;
Expand Down Expand Up @@ -725,6 +729,21 @@ function parseModelString(
// BigInt
return BigInt(value.slice(2));
}
case 'E': {
if (__DEV__) {
// In DEV mode we allow indirect eval to produce functions for logging.
// This should not compile to eval() because then it has local scope access.
try {
// eslint-disable-next-line no-eval
return (0, eval)(value.slice(2));
} catch (x) {
// We currently use this to express functions so we fail parsing it,
// let's just return a blank function as a place holder.
return function () {};
}
}
// Fallthrough
}
default: {
// We assume that anything else is a reference ID.
const id = parseInt(value.slice(1), 16);
Expand Down Expand Up @@ -1063,6 +1082,27 @@ function resolveDebugInfo(
chunkDebugInfo.push(debugInfo);
}

function resolveConsoleEntry(
response: Response,
value: UninitializedModel,
): void {
if (!__DEV__) {
// These errors should never make it into a build so we don't need to encode them in codes.json
// eslint-disable-next-line react-internal/prod-error-codes
throw new Error(
'resolveConsoleEntry should never be called in production mode. This is a bug in React.',
);
}

const payload: [string, string, mixed] = parseModel(response, value);
const methodName = payload[0];
// TODO: Restore the fake stack before logging.
// const stackTrace = payload[1];
const args = payload.slice(2);
// eslint-disable-next-line react-internal/no-production-logging
console[methodName].apply(console, args);
}

function mergeBuffer(
buffer: Array<Uint8Array>,
lastChunk: Uint8Array,
Expand Down Expand Up @@ -1212,6 +1252,13 @@ function processFullRow(
resolveDebugInfo(response, id, debugInfo);
return;
}
// Fallthrough to share the error with Console entries.
}
case 87 /* "W" */: {
if (__DEV__) {
resolveConsoleEntry(response, row);
return;
}
throw new Error(
'Failed to read a RSC payload created by a development version of React ' +
'on the server while using a production version on the client. Always use ' +
Expand Down
41 changes: 41 additions & 0 deletions packages/react-client/src/__tests__/ReactFlight-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1995,4 +1995,45 @@ describe('ReactFlight', () => {
</div>,
);
});

// @gate enableServerComponentLogs && __DEV__
it('replays logs, but not onError logs', async () => {
function foo() {
return 'hello';
}
function ServerComponent() {
console.log('hi', {prop: 123, fn: foo});
throw new Error('err');
}

let transport;
expect(() => {
// Reset the modules so that we get a new overridden console on top of the
// one installed by expect. This ensures that we still emit console.error
// calls.
jest.resetModules();
jest.mock('react', () => require('react/react.react-server'));
ReactServer = require('react');
ReactNoopFlightServer = require('react-noop-renderer/flight-server');
transport = ReactNoopFlightServer.render({root: <ServerComponent />});
}).toErrorDev('err');

const log = console.log;
try {
console.log = jest.fn();
// The error should not actually get logged because we're not awaiting the root
// so it's not thrown but the server log also shouldn't be replayed.
await ReactNoopFlightClient.read(transport);

expect(console.log).toHaveBeenCalledTimes(1);
expect(console.log.mock.calls[0][0]).toBe('hi');
expect(console.log.mock.calls[0][1].prop).toBe(123);
const loggedFn = console.log.mock.calls[0][1].fn;
expect(typeof loggedFn).toBe('function');
expect(loggedFn).not.toBe(foo);
expect(loggedFn.toString()).toBe(foo.toString());
} finally {
console.log = log;
}
});
});
Loading

0 comments on commit 19c3266

Please sign in to comment.