Commit Graph

11 Commits

Author SHA1 Message Date
Hendrik Liebau 6f4d94ac88 Stream Cache Components dev render instead of restarting on cache miss (#94457)
When Cache Components is enabled, `next dev` previously simulated a
production loading experience on every cold request. The render did a
prospective pass to detect cache misses, and on any miss it waited for
every cache to fill via `cacheSignal.cacheReady()` and then restarted
the render with warm caches before streaming anything, so the browser
saw nothing until the slowest cache had filled. Every cold load blocked
on cache population.

This change replaces the restart-on-cache-miss flow with a single
non-abandoning staged render that streams immediately and fills caches
as a side effect. On a cold load the Suspense fallbacks stream right
away and the cached content resolves as its cache fills; on a warm
reload the staged progression matches the previous no-cache-miss path.
The render is split into clearly owned pieces: `setUpStagedDevRender`
builds the staged controller, cache signal, and resume cache;
`streamStagedRenderInDev{Node,Web}` runs the streaming render and
reports a result once the stream has fully finished; and
`stagedRenderWithCachesInDev{Node,Web}` returns the stream and leaves
the validation follow-up detached so it never blocks the response.

The render advances its stages in sequential tasks, and the stream is
not handed back the instant it exists: it is held until the render has
advanced through the stage whose content belongs in the shell. That is
the static stage for initial loads, HMR refreshes, and plain
navigations, or the runtime stage for client navigations to a route with
a runtime prefetch config, whose runtime-prefetchable content the
navigation's prefetch would have settled. It never waits for the dynamic
stage. Buffering the shell before the first flush keeps the streaming
renderer from emitting a premature Suspense fallback for content that
belongs in the shell, and it mirrors production, where the static shell
(plus runtime-prefetchable content where configured) is served and the
remaining holes stream in as fallbacks.

Two internal reads that would otherwise register as synchronous IO and
wrongly force the render to the dynamic stage, the cache handler's
tag-expiry clock check and the hot reloader's module-scope dev client
id, are now read untracked: via `performance.timeOrigin +
performance.now()` like the `'use cache'` handler, and only in the
browser where the HMR connection reads it, respectively.

Cache Components rules validation now runs in that background follow-up,
once the streamed render has fully settled. `planDevValidation` inspects
the finished render and picks one of three paths: forward an invalid
dynamic usage error the streamed render already recorded and stop (for
example a request API used inside `'use cache'`); validate the streamed
render's own chunks when it neither missed caches nor hit sync IO; or,
when it did either, validate a dedicated warm-cache render instead.
Because that warm render reads the filled caches back rather than
filling them, it can surface an invalid dynamic usage error the cold
streamed render cannot, such as a nested dynamic `use cache` cache life
that propagated to a parent with no explicit `cacheLife`; that error is
forwarded and validation is skipped, just as one recorded by the
streamed render is.

Since cold loads no longer block on cache fills, the transient
cache-status indicator that reflected that wait is no longer emitted; a
follow-up will instead add an indicator that tells the user whether a
render streamed with cache misses, and so wasn't representative of
production.
2026-06-09 10:38:12 +00:00
Hendrik Liebau b6a7714057 Hoist inner 'use cache' functions to reduce function allocations (#85904)
This PR fixes a slight performance regression introduced in #85519 where
inline async function expressions were created for each unique set of
arguments passed to a `'use cache'` function.

For a function like this:

```js
export async function getCachedData(id) {
  'use cache';
  return fetch(`/api/data/${id}`);
}
```

we were previously generating (simplified):

```js
export var $$RSC_SERVER_CACHE_0 = cache("default", "0815", 0, async function(id) {
  return fetch(`/api/data/${id}`);
});
```

In #85519, we restructured this to ensure proper stack frames in error
messages (simplified):

```js
export var $$RSC_SERVER_CACHE_0 = React.cache(function getCachedData() {
  return cache("default", "0815", 0, async function(id) {
    return fetch(`/api/data/${id}`);
  }, arguments);
});
```

However, this introduced a small performance issue: the inner async
function expression was passed inline to the cache wrapper. While
`React.cache` memoizes the outer function, each unique set of arguments
would cause a new inner function object to be allocated.

Now we're generating (simplified):

```js
const $$RSC_SERVER_CACHE_0_INNER = async function getCachedData(id) {
  return fetch(`/api/data/${id}`);
};

export var $$RSC_SERVER_CACHE_0 = React.cache(function getCachedData() {
  return cache("default", "0815", 0, $$RSC_SERVER_CACHE_0_INNER, arguments);
});
```

The cache implementation is now hoisted to module scope with an `_INNER`
suffix as a const declaration with a named function expression. The
function name is preserved to ensure proper stack traces in dev. This
eliminates the repeated function allocations while preserving the
improvements from #85519.
2025-11-10 13:09:59 +01:00
Sebastian "Sebbie" Silbermann 0b58a32c45 [test] assert* -> waitFor* when the util is not instant (#85450) 2025-10-30 14:44:08 +01:00
nextjs-bot 62856be393 Upgrade React from edac0dde-20250723 to 3d14fcf0-20250724 (#82020)
Co-authored-by: Sebastian Sebbie Silbermann <sebastian.silbermann@vercel.com>
2025-07-25 16:53:40 +02:00
Sebastian "Sebbie" Silbermann 0c0dc4865e [sourcemaps] Ensure codeframe when calling Client Functions from Server (#81918)
We just need to give a special name to that module so that we can ignore-list it later.

For Webpack I chose the same approach as https://github.com/vercel/next.js/pull/81229. Turbopack already sourcemapped the generated module.

Closes https://linear.app/vercel/issue/NAR-234

RSPack team is informed. Their compat layer doesn't implement `createFilename`
2025-07-22 18:29:39 +02:00
Sebastian "Sebbie" Silbermann 382b79bcc9 [sourcemaps] Consistent cursor columns (#81375)
Co-authored-by: Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
2025-07-16 20:45:34 +02:00
Sebastian "Sebbie" Silbermann 4dd01eea2f [sourcemaps] Properly devirtualize rsc: URLs (#81554) 2025-07-11 21:45:49 +02:00
Janka Uryga 733e4d6413 test: fix snapshots in failing tests (#79254) 2025-05-15 20:53:15 +00:00
Hendrik Liebau bc7ce5d68d Reland: Fix false-positive "use cache" misplacement error (#79222)
_Relanding #79151, now ignoring TS AST nodes when checking whether all
exported module items are async functions._

This fixes an error where we incorrectly showed the following compiler
error when using Turbopack:

```sh
Ecmascript file had an error
> 1 | 'use cache'
    | ^^^^^^^^^^^
  2 |
  3 | import { useStuff } from './client-module'
  4 |

The "use cache" directive must be at the top of the file.
```

The directive was regarded as not being at the top of the file, because
the React transform (`EcmascriptInputTransform::React`) injects a
variable declaration for React Refresh (e.g. `var _s =
__turbopack_context__.k.signature`) at the top of the file, before the
`"use cache"` directive.

We can fix this by ensuring that the server action transform (should
really be called "server _function_ transform") runs first.

As a consequence, the transform now needs to be able to parse JSX AST
nodes, which was already explicitly implemented.

closes NAR-130

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
2025-05-15 13:06:28 +02:00
Donny/강동윤 de89c8cd01 Revert "Fix false-positive "use cache" misplacement error" (#79160)
Reverts vercel/next.js#79151

It caused a regression like this
```
export type Foo =
     | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Only async functions are allowed to be exported in a "use server" file.
```
2025-05-13 17:21:49 +00:00
Hendrik Liebau c1262aa970 Fix false-positive "use cache" misplacement error (#79151)
This fixes an error where we incorrectly showed the following compiler
error when using Turbopack:

```sh
Ecmascript file had an error
> 1 | 'use cache'
    | ^^^^^^^^^^^
  2 |
  3 | import { useStuff } from './client-module'
  4 |

The "use cache" directive must be at the top of the file.
```

The directive was regarded as not being at the top of the file, because
the React transform (`EcmascriptInputTransform::React`) injects a
variable declaration for React Refresh (e.g. `var _s =
__turbopack_context__.k.signature`) at the top of the file, before the
`"use cache"` directive.

We can fix this by ensuring that the server action transform (should
really be called "server _function_ transform") runs first.

As a consequence, the transform now needs to be able to parse JSX AST
nodes, which was already explicitly implemented.

closes NAR-130
2025-05-13 14:58:02 +02:00