Skip to content

Commit

Permalink
ensure router cache updates reference the latest cache values (#66681)
Browse files Browse the repository at this point in the history
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:

- 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

- 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

- 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

- 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

- 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

Closes NEXT-
Fixes #

-->
  • Loading branch information
ztanner committed Jun 10, 2024
1 parent f7ec039 commit 44661c2
Show file tree
Hide file tree
Showing 17 changed files with 152 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ function navigateReducer_noPPR(
}

let currentTree = state.tree
const currentCache = state.cache
let currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = []
for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice(
Expand Down Expand Up @@ -245,6 +245,9 @@ function navigateReducer_noPPR(
mutable.cache = cache
} else if (applied) {
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
Expand Down Expand Up @@ -331,7 +334,7 @@ function navigateReducer_PPR(
}

let currentTree = state.tree
const currentCache = state.cache
let currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = []
// 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
Expand Down Expand Up @@ -496,6 +499,9 @@ function navigateReducer_PPR(
mutable.cache = cache
} else if (applied) {
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
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { nextTestSetup } from 'e2e-utils'
import { browserConfigWithFixedTime, fastForwardTo } from './test-utils'
import { findAllTelemetryEvents } from 'next-test-utils'
import path from 'path'

describe('app dir client cache semantics (experimental staleTimes)', () => {
describe('dynamic: 0', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
files: path.join(__dirname, 'fixtures', 'regular'),
nextConfig: {
experimental: { staleTimes: { dynamic: 0 } },
},
Expand Down Expand Up @@ -193,7 +194,7 @@ describe('app dir client cache semantics (experimental staleTimes)', () => {

describe('static: 180', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
files: path.join(__dirname, 'fixtures', 'regular'),
nextConfig: {
experimental: { staleTimes: { static: 180 } },
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
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)
})
})
})
3 changes: 2 additions & 1 deletion test/e2e/app-dir/app-client-cache/client-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import {
fastForwardTo,
getPathname,
} from './test-utils'
import path from 'path'

createNextDescribe(
'app dir client cache semantics',
{
files: __dirname,
files: path.join(__dirname, 'fixtures', 'regular'),
},
({ next, isNextDev }) => {
if (isNextDev) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function Page({ params }) {
return (
<div>
Catchall <pre>{JSON.stringify(params)}</pre>{' '}
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page() {
return <div>Root Breadcrumb</div>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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>
</>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Link from 'next/link'

export default function Page() {
return (
<div>
<Link href="/0" prefetch={true}>
To Dynamic Page
</Link>
</div>
)
}

0 comments on commit 44661c2

Please sign in to comment.