Commit Graph

180 Commits

Author SHA1 Message Date
Colin McDonnell 56ffca8b9e
Add Bun streaming server renderer (#25597)
Add support for Bun server renderer
2022-11-17 13:15:56 -08:00
Andrew Clark 1a902623a8
Unwrap sync resolved thenables without suspending (#25615)
If a thenable resolves synchronously, `use` should unwrap its result
without suspending or interrupting the component's execution.
2022-11-02 13:53:23 -04:00
Sebastian Markbåge 765805bf88
Fix type check for null (#25595) 2022-10-31 17:29:01 -04:00
Andrew Clark d2a0176a13
Detect and warn if use(promise) is wrapped with try/catch block (#25543)
The old (unstable) mechanism for suspending was to throw a promise. The
purpose of throwing is to interrupt the component's execution, and also
to signal to React that the interruption was caused by Suspense as
opposed to some other error.

A flaw is that throwing is meant to be an implementation detail — if
code in userspace catches the promise, it can lead to unexpected
behavior.

With `use`, userspace code does not throw promises directly, but `use`
itself still needs to throw something to interrupt the component and
unwind the stack.

The solution is to throw an internal error. In development, we can
detect whether the error was caught by a userspace try/catch block and
log a warning — though it's not foolproof, since a clever user could
catch the object and rethrow it later.

The error message includes advice to move `use` outside of the try/catch
block.

I did not yet implement the warning in Flight.
2022-10-28 17:46:03 -04:00
Andrew Clark fa77f52e74 Unify promise switch statements
There are two different switch statements that we use to unwrap a
`use`-ed promise, but there really only needs to be one. This was a
factoring artifact that arose because I implemented the yieldy `status`
instrumentation thing before I implemented `use` (for promises that are
thrown directly during render, which is the old Suspense pattern that
will be superseded by `use`).
2022-10-23 18:43:30 -04:00
Andrew Clark 7fc3eefd85 Revert yieldy behavior for non-use Suspense (in Flight, too)
Same as #25537 but for Flight.

I was going to wait to do this later because the temporary
implementation of async components uses some of the same code that
non-used wakables do, but it's not so bad. I just had to inline one bit
of code, which we'll remove when we unify the implementation with `use`.
2022-10-23 18:43:30 -04:00
Sebastian Markbåge 1d3fc9c9c4
Bug fix when resolving cache (#25545)
We must use the asynclocalstorage one if it's available.
2022-10-23 14:12:47 -04:00
Sebastian Markbåge cce18e3504
[Flight] Use AsyncLocalStorage to extend the scope of the cache to micro tasks (#25542)
This extends the scope of the cache and fetch instrumentation using
AsyncLocalStorage for microtasks. This is an intermediate step. It sets
up the dispatcher only once. This is unique to RSC because it uses the
react.shared-subset module for its shared state.

Ideally we should support multiple renderers. We should also have this
take over from an outer SSR's instrumented fetch. We should also be able
to have a fallback to global state per request where AsyncLocalStorage
doesn't exist and then the whole client-side solutions. I'm still
figuring out the right wiring for that so this is a temporary hack.
2022-10-23 01:06:58 -04:00
Andrew Clark dd5c208257
Revert yieldy behavior for non-use Suspense (#25537)
To derisk the rollout of `use`, and simplify the implementation, this
reverts the yield-to-microtasks behavior for promises that are thrown
directly (as opposed to being unwrapped by `use`).

We may add this back later. However, the plan is to deprecate throwing a
promise directly and migrate all existing Suspense code to `use`, so the
extra code probably isn't worth it.
2022-10-22 17:52:20 -04:00
Josh Story 934177598e
fix transposed escape functions (#25534)
escapeTextForBrowser accepts any type so flow did not identify that we
were escaping a Chunk rather than a string. It's tricky because we
sometimes want to be able to escape non strings.

I've also updated the types for `Chunk` and `escapeTextForBrowser`
so that we should be able to catch this statically in the future.

The reason this did not show up in tests is almost all of our tests of
float (the areas affected by transpositions) are tested using the Node
runtime where a chunk type is a string. It may be wise to run these
tests in every runtime in the future or at least make sure there is
broad representation of resources in each specific runtime test suite.
2022-10-22 09:56:40 -07:00
Sebastian Markbåge 65e32e58b6
Add fetch Instrumentation to Dedupe Fetches (#25516)
* Add fetch instrumentation in cached contexts

* Avoid unhandled rejection errors for Promises that we intentionally ignore

In the final passes, we ignore the newly generated Promises and use
the previous ones. This ensures that if those generate errors, that we
intentionally ignore those.

* Add extra fetch properties if there were any
2022-10-19 18:37:00 -04:00
lauren 3cc792bfb5
[useEvent] Non-stable function identity (#25473)
* [useEvent] Non-stable function identity

Since useEvent shouldn't go in the dependency list of whatever is
consuming it (which is enforced by the fact that useEvent functions are
always locally created and never passed by reference), its identity
doesn't matter. Effectively, this PR is a runtime assertion
that you can't rely on the return value of useEvent to be stable.

* Test: Events should see latest bindings

The key feature of useEvent that makes it different from useCallback
is that events always see the latest committed values. There's no such
thing as a "stale" event handler.

* Don't queue a commit effect on mount

* Inline event function wrapping

- Inlines wrapping of the callback
- Use a mutable ref-style object instead of a callable object
- Fix types

Co-authored-by: Andrew Clark <git@andrewclark.io>
2022-10-19 11:59:27 -07:00
Andrew Clark 9cdf8a99ed
[Codemod] Update copyright header to Meta (#25315)
* Facebook -> Meta in copyright

rg --files | xargs sed -i 's#Copyright (c) Facebook, Inc. and its affiliates.#Copyright (c) Meta Platforms, Inc. and affiliates.#g'

* Manual tweaks
2022-10-18 11:19:24 -04:00
Sebastian Markbåge bc358362a6
[Flight] Improve Error Messages when Invalid Object is Passed to Client/Host Components (#25492)
* Print built-in specific error message for toJSON

This is a better message for Date.

Also, format the message to highlight the affected prop.

* Describe error messages using JSX elements in DEV

We don't have access to the grand parent objects on the stack so we stash
them on weakmaps so we can access them while printing error messages.

Might be a bit slow.

* Capitalize Server/Client Component

* Special case errror messages for children of host components

These are likely meant to be text content if they're not a supported object.

* Update error messages
2022-10-16 21:49:17 -04:00
Joseph Savona 69c7246d9d
Initialize useMemoCache with sentinel values (#25465)
* Flush out useMemoCache API

* rename symbol

* rename symbol.for string name

* workaround symbol export not working in unit tests
2022-10-14 15:00:31 -07:00
Sebastian Markbåge 3b814327e2
Allow Async Functions to be used in Server Components (#25479)
This is a temporary step until we allow Promises everywhere.

Currently this serializes to a Lazy which can then be consumed in this same
slot by the client.
2022-10-14 15:09:33 -04:00
Sebastian Markbåge a8c16a0040
Split Cache into its own Dispatcher (#25474)
* Missing Hooks

* Remove www forks. These can use __SECRET... instead.

* Move cache to separate dispatcher

These will be available in more contexts than just render.
2022-10-12 23:13:39 -04:00
Jan Kassens ea04a486a7
Flow: remove unused suppressions (#25424)
Removes $FlowFixMe's that are no longer needed.

Used flow/tool from the Flow repo:

```
 ~/Developer/flow/tool update-suppressions .
```
2022-10-04 16:18:12 -04:00
Jan Kassens 3b6826ed9e Flow: inference_mode=constrain_writes
This mode is going to be the new default in Flow going forward.
There was an unfortuante large number of suppressions in this update.

More on the changes can be found in this [Flow blog post](https://medium.com/flow-type/new-flow-language-rule-constrained-writes-4c70e375d190).

Added some of the required annotations using the provided codemod:

```sh
node_modules/.bin/flow codemod annotate-declarations --write .
```

ghstack-source-id: 0b168e1b23
Pull Request resolved: https://github.com/facebook/react/pull/25422
2022-10-04 15:49:48 -04:00
Jan Kassens 9f8a98a390 Flow upgrade to 0.153
- method unbinding is no longer supported in Flow for soundness, this added a bunch of suppressions
- Flow now prevents objects to be supertypes of interfaces/classes

ghstack-source-id: d7749cbad8
Pull Request resolved: https://github.com/facebook/react/pull/25412
2022-10-04 11:30:06 -04:00
Jan Kassens 64fe791be8 Flow upgrade to 0.146
This upgrade made more expressions invalidate refinements. In some
places this lead to a large number of suppressions that I automatically
suppressed and should be followed up on when the code is touched.
I think most of them might require either manual annotations or moving
a value into a const to allow refinement.

ghstack-source-id: a45b40abf0
Pull Request resolved: https://github.com/facebook/react/pull/25410
2022-10-04 11:01:50 -04:00
Jan Kassens 9143864ae1
Flow: well formed exports for smaller packages (#25361)
Enforces well formed exports for packages where the fixes are small.
2022-10-03 16:52:41 -04:00
Josh Story 7b25b961df
[Fizz/Float] Float for stylesheet resources (#25243)
* [Fizz/Float] Float for stylesheet resources

This commit implements Float in Fizz and on the Client. The initial set of supported APIs is roughly

1. Convert certain stylesheets into style Resources when opting in with precedence prop
2. Emit preloads for stylesheets and explicit preload tags
3. Dedupe all Resources by href
4. Implement ReactDOM.preload() to allow for imperative preloading
5. Implement ReactDOM.preinit() to allow for imperative preinitialization

Currently supports
1. style Resources (link rel "stylesheet")
2. font Resources (preload as "font")

later updates will include support for scripts and modules
2022-09-30 16:14:04 -07:00
Lauren Tan 3517bd9f77
Refactor useEvent (#25336)
* Refactor useEvent

Previously, the useEvent implementation made use of effect infra under
the hood. This was a lot of extra overhead for functionality we didn't
use (events have no deps, and no clean up functions). This PR refactors
the implementation to instead use a queue to ensure that the callback is
stable across renders.

Additionally, the function signature was updated to infer the callback's argument types and return value. While this doesn't affect anything internal it more accurately describes what's being passed.
2022-09-29 13:45:27 -07:00
Sebastian Markbåge 97d75c9c8b
Move react-dom implementation files to react-dom-bindings (#25345)
This lets us share it with react-server-dom-webpack while still having a
dependency on react-dom. It also makes somewhat sense from a bundling
perspective since react-dom is an external to itself.
2022-09-28 19:05:50 -04:00
dan 3de9264496
[Fizz] experimental_useEvent (#25325)
* [Fizz] useEvent

* Use same message on client and server
2022-09-27 20:42:16 +01:00
Josh Story efc6a08e98
[Flight] Implement error digests for Flight runtime and expose errorInfo in getDerivedStateFromError (#25302)
Similar to Fizz, Flight now supports a return value from the user provided onError option. If a value is returned from onError it will be serialized and provided to the client.

The digest is stashed on the constructed Error on the client as .digest
2022-09-23 13:19:29 -07:00
Sebastian Markbåge 60fbb7b143
[Flight] Implement FlightClient in terms of Thenable/Promises instead of throwing Promises (#25260)
* [Flight] Align Chunks with Thenable used with experimental_use

Use the field names used by the Thenable data structure passed to use().
These are considered public in this model.

This adds another field since we use a separate field name for "reason".

* Implement Thenable Protocol on Chunks

This doesn't just ping but resolves/rejects with the value.

* Subclass Promises

* Pass key through JSON parsing

* Wait for preloadModules before resolving module chunks

* Initialize lazy resolved values before reading the result

* Block a model from initializing if its direct dependencies are pending

If a module is blocked, then we can't complete initializing a model.
However, we can still let it parse, and then fill in the missing pieces
later.

We need to block it from resolving until all dependencies have filled in
which we can do with a ref count.

* Treat blocked modules or models as a special status

We currently loop over all chunks at the end to error them if they're
still pending. We shouldn't do this if they're pending because they're
blocked on an external resource like a module because the module might not
resolve before the Flight connection closes and that's not an error.

In an alternative solution I had a set that tracked pending chunks and
removed one at a time. While the loop at the end is faster it's more
work as we go.

I figured the extra status might also help debugging.

For modules we can probably assume no forward references, and the first
async module we can just use the promise as the chunk.

So we could probably get away with this only on models that are blocked by
modules.
2022-09-14 20:13:33 -04:00
Jan Kassens 346c7d4c43
straightford explicit types (#25253) 2022-09-13 17:57:38 -04:00
mofeiZ 3613284dce
experimental_use(context) for server components and ssr (#25226)
implements the experimental use(context) API for the server components (Flight) and SSR (Fizz) runtimes
2022-09-09 21:19:28 -04:00
Jan Kassens 8003ab9cf5
Flow: remove explicit object syntax (#25223) 2022-09-09 16:03:48 -04:00
Jan Kassens 8a9e7b6cef
Flow: implicit-inexact-object=error (#25210)
* implicit-inexact-object=error
* default everything ambiguous to exact object
* inexact where exact causes errors
2022-09-09 10:13:58 -04:00
Andrew Clark c28f313e6d
experimental_use(promise) for SSR (#25214)
Follow up to #25084 and #25207. Implements experimental_use(promise) API
in the SSR runtime (Fizz).

This is largely a copy-paste of the Flight implementation. I have
intentionally tried to keep both as close as possible.
2022-09-08 21:47:33 -04:00
Jan Kassens a473d08fce
Update to Flow from 0.97 to 0.122 (#25204)
* flow 0.122
* update ReactModel type
2022-09-08 11:46:07 -04:00
Andrew Clark 7028ce7456
experimental_use(promise) for Server Components (#25207)
Follow up to #25084. Implements experimental_use(promise) API in 
the Server Components runtime (Flight).

The implementation is much simpler than in Fiber because there is no
state. Even the "state" added in this PR — to track the result of each
promise across attempts — is reset as soon as a component 
successfully renders without suspending.

There are also fewer caveats around neglecting to cache a promise
because the state of the promises is preserved even if we switch to a
different task.

Server Components is the primary runtime where this API is intended to
be used.

The last runtime where we need to implement this is the server renderer
(Fizz).
2022-09-07 22:27:04 -04:00
Sebastian Markbåge 36c908a6c8
Don't use the Flight terminology in public error messages (#25166) 2022-08-31 23:07:56 -04:00
Sebastian Markbåge 8d1b057ec1
[Flight] Minor error handling fixes (#25151)
* Fix error handling when the Flight client itself errors

* Serialize references to errors in the error priority queue

It doesn't make sense to emit references to future values at higher pri
than the value that they're referencing.

This ensures that we don't emit hard forward references to values that
don't yet exist.
2022-08-31 18:40:17 -04:00
Sebastian Markbåge d0f396651b
Allow functions to be used as module references (#25137) 2022-08-25 07:47:38 -04:00
Joseph Savona 9e67e7a315
Scaffolding for useMemoCache hook (#25123)
* Scaffolding for useMemoCache hook
* cleanup leftovers from copy/paste of use() diff

Co-authored-by: Andrew Clark <git@andrewclark.io>
2022-08-23 09:36:02 +01:00
Josh Story 6ef466c681
make preamble and postamble types explicit and fix typo (#25102) 2022-08-16 12:17:49 +01:00
Josh Story 796d31809b
Implement basic stylesheet Resources for react-dom (#25060)
Implement basic support for "Resources". In the context of this commit, the only thing that is currently a Resource are

<link rel="stylesheet" precedence="some-value" ...>

Resources can be rendered anywhere in the react tree, even outside of normal parenting rules, for instance you can render a resource before you have rendered the <html><head> tags for your application. In the stream we reorder this so the browser always receives valid HTML and resources are emitted either in place (normal circumstances) or at the top of the <head> (when you render them above or before the <head> in your react tree)

On the client, resources opt into an entirely different hydration path. Instead of matching the location within the Document these resources are queried for in the entire document. It is an error to have more than one resource with the same href attribute.

The use of precedence here as an opt-in signal for resourcifying the link is in preparation for a more complete Resource implementation which will dedupe resource references (multiple will be valid), hoist to the appropriate container (body, head, or elsewhere), order (according to precedence) and Suspend boundaries that depend on them. More details will come in the coming weeks on this plan.

This feature is gated by an experimental flag and will only be made available in experimental builds until some future time.
2022-08-12 13:27:53 -07:00
Andrew Clark 2c7dea7365
Implement Offscreen in Fizz (#24988)
During server rendering, a visible Offscreen subtree acts exactly like a
fragment: a pure indirection.

A hidden Offscreen subtree is not server rendered at all. It's ignored
during hydration, too. Prerendering happens only on the client. We
considered prerendering hidden trees on the server, too, but our
conclusion is that it's a waste of bytes and server computation. We
can't think of any compelling cases where it's the right trade off. (If
we ever change our mind, though, the way we'll likely model it is to
treat it as if it's a Suspense boundary with an empty fallback.)
2022-07-26 00:35:51 -04:00
Sebastian Markbåge 56389e81ff
Abort Flight (#24754)
Add aborting to the Flight Server. This encodes the reason as an "error"
row that gets thrown client side. These are still exposed in prod which
is a follow up we'll still have to do to encode them as digests instead.

The error is encoded once and then referenced by each row that needs to
be updated.
2022-06-19 11:05:41 -04:00
Sebastian Markbåge f796fa13ad
Rename Segment to Task in Flight (#24753)
In Fizz this got split into Task and Segment. We don't have a concept of
Segment in Flight yet because we don't inline multiple segments into one
"Row". We just emit one "Row" for each Segment if something suspends.

This makes Flight non-deterministic atm but that's something we'll want to
address.

Regardless, right now, this is more like a Task than a Segment.
2022-06-18 15:02:11 -04:00
Sebastian Markbåge 0f0aca3ab3
Aborting early should not infinitely suspend (#24751)
Before this change we weren't calling onError nor onFatalError if you abort
before completing the shell.

This means that the render never completes and hangs.

Aborting early can happen before even creating the stream for AbortSignal,
before rendering starts in Node since there's an setImmediate atm, or
during rendering.
2022-06-18 11:01:58 -04:00
Josh Story b345523528
[Fizz] Support abort reasons (#24680)
* [Fizz] Support abort reasons

Fizz supports aborting the render but does not currently accept a reason. The various render functions that use Fizz have some automatic and some user-controlled abort semantics that can be useful to communicate with the running program and users about why an Abort happened.

This change implements abort reasons for renderToReadableStream and renderToPipeable stream as well as legacy renderers such as renderToString and related implementations.

For AbortController implementations the reason passed to the abort method is forwarded to Fizz and sent to the onError handler. If no reason is provided the AbortController should construct an AbortError DOMException and as a fallback Fizz will generate a similar error in the absence of a reason

For pipeable  streams, an abort function is returned alongside pipe which already accepted a reason. That reason is now forwarded to Fizz and the implementation described above.

For legacy renderers there is no exposed abort functionality but it is used internally and the reasons provided give useful context to, for instance to the fact that Suspense is not supported in renderToString-like renderers
2022-06-07 22:36:09 -07:00
Josh Story 4f29ba1cc5
support errorInfo in onRecoverableError (#24591)
* extend onRecoverableError API to support errorInfo

errorInfo has been used in Error Boundaries wiht componentDidCatch for a while now. To date this metadata only contained a componentStack. onRecoverableError only receives an error (type mixed) argument and thus providing additional error metadata was not possible without mutating user created mixed objects.

This change modifies rootConcurrentErrors rootRecoverableErrors, and hydrationErrors so all expect CapturedValue types. additionally a new factory function allows the creation of CapturedValues from a value plus a hash and stack.

In general, client derived CapturedValues will be created using the original function which derives a componentStack from a fiber and server originated CapturedValues will be created using with a passed in hash and optional componentStack.
2022-06-06 14:23:32 -07:00
Josh Story dd4950c90e
[Flight] Implement useId hook (#24172)
* Implements useId hook for Flight server.

The approach for ids for Flight is different from Fizz/Client where there is a need for determinancy. Flight rendered elements will not be rendered on the client and as such the ids generated in a request only need to be unique. However since FLight does support refetching subtrees it is possible a client will need to patch up a part of the tree rather than replacing the entire thing so it is not safe to use a simple incrementing counter. To solve for this we allow the caller to specify a prefix. On an initial fetch it is likely this will be empty but on refetches or subtrees we expect to have a client `useId` provide the prefix since it will guaranteed be unique for that subtree and thus for the entire tree. It is also possible that we will automatically provide prefixes based on a client/Fizz useId on refetches

in addition to the core change I also modified the structure of options for renderToReadableStream where `onError`, `context`, and the new `identifierPrefix` are properties of an Options object argument to avoid the clumsiness of a growing list of optional function arguments.

* defend against useId call outside of rendering

* switch to S from F for Server Component ids

* default to empty string identifier prefix

* Add a test demonstrating that there is no warning when double rendering on the client a server component that used useId

* lints and gates
2022-05-31 14:53:32 -07:00
Josh Story aec575914a
[Fizz] Send errors down to client (#24551)
* use return from onError

* export getSuspenseInstanceFallbackError

* stringToChunk

* return string from onError in downstream type signatures

* 1 more type

* support encoding errors in html stream and escape user input

This commit adds another way to get errors to the suspense instance by encoding them as dataset properties of a template element at the head of the boundary. Previously if there was an error before the boundary flushed there was no way to stream the error to the client because there would never be a client render instruction.

Additionally the error is sent in 3 parts

1) error hash - this is always sent (dev or prod) if one is provided
2) error message - Dev only
3) error component stack - Dev only, this now captures the stack at the point of error

Another item addressed in this commit is the escaping of potentially unsafe data. all error components are escaped as test for browers when written into the html and as javascript strings when written into a client render instruction.

* nits

Co-authored-by: Marco Salazar <salazarm@fb.com>
2022-05-29 23:07:10 -07:00
Josh Story a2766387ef
[Fizz] Improve text separator byte efficiency (#24630)
* [Fizz] Improve text separator byte efficiency

Previously text separators were inserted following any Text node in Fizz. This increases bytes sent when streaming and in some cases such as title elements these separators are not interpreted as comment nodes and leak into the visual aspects of a page as escaped text.

The reason simple tracking on the last pushed type doesn't work is that Segments can be filled in asynchronously later and so you cannot know in a single pass whether the preceding content was a text node or not. This commit adds a concept of TextEmbedding which provides a best effort signal to Segments on whether they are embedded within text. This allows the later resolution of that Segment to add text separators when possibly necessary but avoid them when they are surely not.

The current implementation can only "peek" head if the segment is a the Root Segment or a Suspense Boundary Segment. In these cases we know there is no trailing text embedding and we can eliminate the separator at the end of the segment if the last emitted element was Text. In normal Segments we cannot peek and thus have to assume there might be a trailing text embedding and we issue a separator defensively. This should be rare in practice as it is assumed most components that will cause segment creation will also emit some markup at the edges.

* [Fizz] Improve separator efficiency when flushing delayed segments

The method by which we get segment markup into the DOM differs depending on when the Segment resolves.

If a Segment resolves before flushing begins for it's parent it will be emitted inline with the parent markup. In these cases separators may be necessary because they are how we clue the browser into breakup up text into distinct nodes that will later match up with what will be hydrated on the client.

If a Segment resolves after flushing has happened a script will be used to patch up the DOM in the client. when this happens if there are any text nodes on the boundary of the patch they won't be "merged" and thus will continue to have distinct representation as Nodes in the DOM. Thus we can avoid doing any separators at the boundaries in these cases.

After applying these changes the only time you will get text separators as follows

* in between serial text nodes that emit at the same time - these are necessary and cannot be eliminated unless we stop relying on the browser to automatically parse the correct text nodes when processing this HTML
* after a final text node in a non-boundary segment that resolves before it's parent has flushed - these are sometimes extraneous, like when the next emitted thing is a non-Text node.

In all other cases text separators should be omitted which means the general byte efficiency of this approach should be pretty good
2022-05-28 08:30:38 -07:00