Unverified Commit 25d3581b authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

ensure router cache updates reference the latest cache values (#66681)

During navigations, the `FlightDataPath` property from the server
response can be an array if there are multiple parallel routes (eg,
`children` and `slot`). When we apply server response to the router
cache, we might call `applyFlightData` for each segment path, which will
copy existing cache values and insert new ones depending on what
changed.

However, the `existingCache` argument that we pass to this function is
the cache at the start of the navigation. That means subsequent calls to
`applyFlightData` will reference the cache _before_ updates are made to
it. This will cause it to erroneously think it needs to lazy fetch for
missing data.

<!-- 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 #

-->
parent 3c99b8ca
...@@ -167,7 +167,7 @@ function navigateReducer_noPPR( ...@@ -167,7 +167,7 @@ function navigateReducer_noPPR(
updatedCanonicalUrl.split('#', 1)[0] updatedCanonicalUrl.split('#', 1)[0]
let currentTree = state.tree let currentTree = state.tree
const currentCache = state.cache let currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = [] let scrollableSegments: FlightSegmentPath[] = []
for (const flightDataPath of flightData) { for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice( const flightSegmentPath = flightDataPath.slice(
...@@ -258,6 +258,9 @@ function navigateReducer_noPPR( ...@@ -258,6 +258,9 @@ function navigateReducer_noPPR(
mutable.cache = cache mutable.cache = cache
} else if (applied) { } else if (applied) {
mutable.cache = cache mutable.cache = cache
// If we applied the cache, we update the "current cache" value so any other
// segments in the FlightDataPath will be able to reference the updated cache.
currentCache = cache
} }
currentTree = newTree currentTree = newTree
...@@ -352,7 +355,7 @@ function navigateReducer_PPR( ...@@ -352,7 +355,7 @@ function navigateReducer_PPR(
updatedCanonicalUrl.split('#', 1)[0] updatedCanonicalUrl.split('#', 1)[0]
let currentTree = state.tree let currentTree = state.tree
const currentCache = state.cache let currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = [] let scrollableSegments: FlightSegmentPath[] = []
// TODO: In practice, this is always a single item array. We probably // TODO: In practice, this is always a single item array. We probably
// aren't going to every send multiple segments, at least not in this // aren't going to every send multiple segments, at least not in this
...@@ -522,6 +525,9 @@ function navigateReducer_PPR( ...@@ -522,6 +525,9 @@ function navigateReducer_PPR(
mutable.cache = cache mutable.cache = cache
} else if (applied) { } else if (applied) {
mutable.cache = cache mutable.cache = cache
// If we applied the cache, we update the "current cache" value so any other
// segments in the FlightDataPath will be able to reference the updated cache.
currentCache = cache
} }
} }
......
...@@ -7,10 +7,11 @@ import { ...@@ -7,10 +7,11 @@ import {
fastForwardTo, fastForwardTo,
getPathname, getPathname,
} from './test-utils' } from './test-utils'
import path from 'path'
describe('app dir client cache semantics (default semantics)', () => { describe('app dir client cache semantics (default semantics)', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: path.join(__dirname, 'fixtures', 'regular'),
}) })
if (isNextDev) { if (isNextDev) {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { browserConfigWithFixedTime, fastForwardTo } from './test-utils' import { browserConfigWithFixedTime, fastForwardTo } from './test-utils'
import { findAllTelemetryEvents } from 'next-test-utils' import { findAllTelemetryEvents } from 'next-test-utils'
import path from 'path'
describe('app dir client cache semantics (experimental staleTimes)', () => { describe('app dir client cache semantics (experimental staleTimes)', () => {
describe('dynamic: 0', () => { describe('dynamic: 0', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: path.join(__dirname, 'fixtures', 'regular'),
nextConfig: { nextConfig: {
experimental: { staleTimes: { dynamic: 0 } }, experimental: { staleTimes: { dynamic: 0 } },
}, },
...@@ -242,7 +243,7 @@ describe('app dir client cache semantics (experimental staleTimes)', () => { ...@@ -242,7 +243,7 @@ describe('app dir client cache semantics (experimental staleTimes)', () => {
describe('static: 180', () => { describe('static: 180', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: path.join(__dirname, 'fixtures', 'regular'),
nextConfig: { nextConfig: {
experimental: { staleTimes: { static: 180 } }, experimental: { staleTimes: { static: 180 } },
}, },
...@@ -360,7 +361,7 @@ describe('app dir client cache semantics (experimental staleTimes)', () => { ...@@ -360,7 +361,7 @@ describe('app dir client cache semantics (experimental staleTimes)', () => {
describe('dynamic: 0, static: 0', () => { describe('dynamic: 0, static: 0', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: path.join(__dirname, 'fixtures', 'regular'),
nextConfig: { nextConfig: {
experimental: { staleTimes: { dynamic: 0, static: 0 } }, experimental: { staleTimes: { dynamic: 0, static: 0 } },
}, },
......
...@@ -7,11 +7,12 @@ import { ...@@ -7,11 +7,12 @@ import {
fastForwardTo, fastForwardTo,
getPathname, getPathname,
} from './test-utils' } from './test-utils'
import path from 'path'
// This preserves existing tests for the 30s/5min heuristic (previous router defaults) // This preserves existing tests for the 30s/5min heuristic (previous router defaults)
describe('app dir client cache semantics (30s/5min)', () => { describe('app dir client cache semantics (30s/5min)', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: path.join(__dirname, 'fixtures', 'regular'),
nextConfig: { nextConfig: {
experimental: { staleTimes: { dynamic: 30, static: 180 } }, experimental: { staleTimes: { dynamic: 30, static: 180 } },
}, },
......
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { BrowserInterface } from 'next-webdriver'
import {
browserConfigWithFixedTime,
createRequestsListener,
fastForwardTo,
getPathname,
} from './test-utils'
import path from 'path'
describe('app dir client cache with parallel routes', () => {
const { next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'parallel-routes'),
})
if (isNextDev) {
// dev doesn't support prefetch={true}
it('should skip dev', () => {})
return
}
describe('prefetch={true}', () => {
let browser: BrowserInterface
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
})
it('should prefetch the full page', async () => {
const { getRequests, clearRequests } =
await createRequestsListener(browser)
await check(() => {
return getRequests().some(
([url, didPartialPrefetch]) =>
getPathname(url) === '/0' && !didPartialPrefetch
)
? 'success'
: 'fail'
}, 'success')
clearRequests()
await browser
.elementByCss('[href="/0"]')
.click()
.waitForElementByCss('#random-number')
expect(getRequests().every(([url]) => getPathname(url) !== '/0')).toEqual(
true
)
})
it('should re-use the cache for the full page, only for 5 mins', async () => {
const randomNumber = await browser
.elementByCss('[href="/0"]')
.click()
.waitForElementByCss('#random-number')
.text()
await browser.elementByCss('[href="/"]').click()
const number = await browser
.elementByCss('[href="/0"]')
.click()
.waitForElementByCss('#random-number')
.text()
expect(number).toBe(randomNumber)
await browser.eval(fastForwardTo, 5 * 60 * 1000)
await browser.elementByCss('[href="/"]').click()
const newNumber = await browser
.elementByCss('[href="/0"]')
.click()
.waitForElementByCss('#random-number')
.text()
expect(newNumber).not.toBe(randomNumber)
})
})
})
export default function Page({ params }) {
return (
<div>
Catchall <pre>{JSON.stringify(params)}</pre>{' '}
</div>
)
}
export default function Page() {
return <div>Root Breadcrumb</div>
}
import Link from 'next/link'
export default async function Page() {
const randomNumber = await new Promise((resolve) => {
setTimeout(() => {
resolve(Math.random())
}, 1000)
})
return (
<>
<div>
<Link href="/">Back to Home</Link>
</div>
<div id="random-number">{randomNumber}</div>
</>
)
}
export default function Root({ children, breadcrumbs }) {
return (
<html>
<head></head>
<body>
<div>{breadcrumbs}</div>
<div id="root-layout">Root Layout</div>
<div>{children}</div>
</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<Link href="/0" prefetch={true}>
To Dynamic Page
</Link>
</div>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment