File size: 8,629 Bytes
b2cad4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
diff --git a/test/e2e/app-dir/use-cache-after-uncached-io/app/layout.tsx b/test/e2e/app-dir/use-cache-after-uncached-io/app/layout.tsx
new file mode 100644
index 00000000..716a8db3
--- /dev/null
+++ b/test/e2e/app-dir/use-cache-after-uncached-io/app/layout.tsx
@@ -0,0 +1,9 @@
+import { ReactNode } from 'react'
+
+export default function Root({ children }: { children: ReactNode }) {
+  return (
+    <html>
+      <body>{children}</body>
+    </html>
+  )
+}
diff --git a/test/e2e/app-dir/use-cache-after-uncached-io/app/page.tsx b/test/e2e/app-dir/use-cache-after-uncached-io/app/page.tsx
new file mode 100644
index 00000000..4f162a87
--- /dev/null
+++ b/test/e2e/app-dir/use-cache-after-uncached-io/app/page.tsx
@@ -0,0 +1,9 @@
+import { LinkAccordion } from '../components/link-accordion'
+
+export default function Page() {
+  return (
+    <main>
+      <LinkAccordion href="/uses-cache">/uses-cache</LinkAccordion>
+    </main>
+  )
+}
diff --git a/test/e2e/app-dir/use-cache-after-uncached-io/app/revalidate-uses-cache/route.ts b/test/e2e/app-dir/use-cache-after-uncached-io/app/revalidate-uses-cache/route.ts
new file mode 100644
index 00000000..1ba4704e
--- /dev/null
+++ b/test/e2e/app-dir/use-cache-after-uncached-io/app/revalidate-uses-cache/route.ts
@@ -0,0 +1,31 @@
+import { revalidatePath, revalidateTag } from 'next/cache'
+
+type State = { attempts: number; executions: number; settlements: number }
+
+function getState(): State {
+  const testGlobal = globalThis as typeof globalThis & {
+    __nextUseCacheAfterUncachedIOState?: State
+  }
+  return (testGlobal.__nextUseCacheAfterUncachedIOState ??= {
+    attempts: 0,
+    executions: 0,
+    settlements: 0,
+  })
+}
+
+export function GET() {
+  return Response.json(getState())
+}
+
+/** Evicts the entry so the prefetch's fill actually runs. */
+export async function POST() {
+  revalidateTag('data', { expire: 0 })
+  revalidatePath('/uses-cache')
+
+  const state = getState()
+  state.attempts = 0
+  state.executions = 0
+  state.settlements = 0
+
+  return Response.json({ ok: true })
+}
diff --git a/test/e2e/app-dir/use-cache-after-uncached-io/app/uses-cache/page.tsx b/test/e2e/app-dir/use-cache-after-uncached-io/app/uses-cache/page.tsx
new file mode 100644
index 00000000..1ea041ab
--- /dev/null
+++ b/test/e2e/app-dir/use-cache-after-uncached-io/app/uses-cache/page.tsx
@@ -0,0 +1,53 @@
+import { cacheLife, cacheTag } from 'next/cache'
+import { Suspense } from 'react'
+
+type State = { attempts: number; executions: number; settlements: number }
+
+function getState(): State {
+  const testGlobal = globalThis as typeof globalThis & {
+    __nextUseCacheAfterUncachedIOState?: State
+  }
+  return (testGlobal.__nextUseCacheAfterUncachedIOState ??= {
+    attempts: 0,
+    executions: 0,
+    settlements: 0,
+  })
+}
+
+export default function Page() {
+  return (
+    <main>
+      This page uses a cache
+      <Suspense fallback={<p id="fallback">Loading…</p>}>
+        <Late />
+      </Suspense>
+    </main>
+  )
+}
+
+async function Late() {
+  // In a prerender, this will resolve after the prerender is already aborted
+  // (both in prospective and final prerenders)
+  await new Promise((resolve) => setTimeout(resolve, 1000))
+
+  getState().attempts++
+  try {
+    const result = await getCachedData()
+    return <p id="data">{result}</p>
+  } finally {
+    getState().settlements++
+    // Retained for compatibility with older versions of this regression test.
+    console.log('after-cache-read')
+  }
+}
+
+async function getCachedData(): Promise<string> {
+  'use cache'
+  cacheLife('hours')
+  cacheTag('data')
+
+  getState().executions++
+  console.log('running getCachedData')
+
+  return 'cached-data: ' + Date.now()
+}
diff --git a/test/e2e/app-dir/use-cache-after-uncached-io/components/link-accordion.tsx b/test/e2e/app-dir/use-cache-after-uncached-io/components/link-accordion.tsx
new file mode 100644
index 00000000..b3bf56b6
--- /dev/null
+++ b/test/e2e/app-dir/use-cache-after-uncached-io/components/link-accordion.tsx
@@ -0,0 +1,32 @@
+'use client'
+import Link from 'next/link'
+import { useState } from 'react'
+
+export function LinkAccordion({
+  href,
+  children,
+  prefetch,
+}: {
+  href: string
+  children: React.ReactNode
+  prefetch?: boolean
+}) {
+  const [isVisible, setIsVisible] = useState(false)
+  return (
+    <>
+      <input
+        type="checkbox"
+        checked={isVisible}
+        onChange={() => setIsVisible(!isVisible)}
+        data-link-accordion={href}
+      />
+      {isVisible ? (
+        <Link href={href} prefetch={prefetch}>
+          {children}
+        </Link>
+      ) : (
+        `${children} (link is hidden)`
+      )}
+    </>
+  )
+}
diff --git a/test/e2e/app-dir/use-cache-after-uncached-io/next.config.ts b/test/e2e/app-dir/use-cache-after-uncached-io/next.config.ts
new file mode 100644
index 00000000..49c8b8d7
--- /dev/null
+++ b/test/e2e/app-dir/use-cache-after-uncached-io/next.config.ts
@@ -0,0 +1,7 @@
+import { NextConfig } from 'next'
+
+const nextConfig: NextConfig = {
+  cacheComponents: true,
+}
+
+export default nextConfig
diff --git a/test/e2e/app-dir/use-cache-after-uncached-io/use-cache-after-uncached-io.test.ts b/test/e2e/app-dir/use-cache-after-uncached-io/use-cache-after-uncached-io.test.ts
new file mode 100644
index 00000000..b4e84ace
--- /dev/null
+++ b/test/e2e/app-dir/use-cache-after-uncached-io/use-cache-after-uncached-io.test.ts
@@ -0,0 +1,90 @@
+import { nextTestSetup } from 'e2e-utils'
+import * as Playwright from 'playwright'
+import { createRouterAct } from '../../../lib/router-act'
+import { retry } from '../../../lib/next-test-utils'
+
+type CacheState = {
+  attempts: number
+  executions: number
+  settlements: number
+}
+
+describe('use cache reached after uncancellable asynchronous work', () => {
+  const { next, isNextStart } = nextTestSetup({
+    files: __dirname,
+  })
+
+  if (isNextStart) {
+    it('does not start an abandoned fill or poison a later request', async () => {
+      // This is a regression test for:
+      // https://github.com/vercel/next.js/issues/96339
+      // Asynchronous work can reach a cache call after its prerender has ended.
+      // That abandoned call must not execute a fill or affect a later live request.
+
+      // Revalidate /uses-cache (and, just to be safe, the cache that it references)
+      // so that we have a fresh prerender we can assert on
+      await next.fetch('/revalidate-uses-cache', { method: 'POST' })
+
+      let page: Playwright.Page
+      const browser = await next.browser('/', {
+        beforePageLoad(p) {
+          page = p
+        },
+      })
+      const act = createRouterAct(page)
+
+      // Prefetch the page, triggering a fresh prerender
+      await act(async () => {
+        await browser
+          .elementByCss('input[data-link-accordion="/uses-cache"]')
+          .click()
+      })
+
+      // Synchronize through a fixture endpoint instead of implementation logs.
+      // The delayed component reached and settled its abandoned cache call, but
+      // the cache function itself must not have started.
+      let abandonedAttempts = 0
+      await retry(async () => {
+        const state = (await next
+          .fetch('/revalidate-uses-cache')
+          .then((response) => response.json())) as CacheState
+        expect(state.attempts).toBeGreaterThan(0)
+        expect(state.executions).toBe(0)
+        expect(state.settlements).toBe(state.attempts)
+        abandonedAttempts = state.attempts
+      })
+
+      // Navigate to the page. The response should include the cache
+      await act(
+        async () => {
+          await browser.elementByCss('a[href="/uses-cache"]').click()
+        },
+
+        { includes: 'cached-data' }
+      )
+
+      const value = await browser.elementByCss('#data').text()
+      expect(value).toMatch(/cached-data: \d+/)
+
+      // The later live render performs the first and only cache fill.
+      expect(
+        (await next
+          .fetch('/revalidate-uses-cache')
+          .then((response) => response.json())) as CacheState
+      ).toEqual({
+        attempts: abandonedAttempts + 1,
+        executions: 1,
+        settlements: abandonedAttempts + 1,
+      })
+    })
+  } else {
+    it('resolves in dev', async () => {
+      // There's no prefetching in dev, so the best we can do is
+      // test that the cache resolves as expected.
+      const browser = await next.browser('/uses-cache')
+      expect(await browser.elementByCss('#data').text()).toMatch(
+        /cached-data: \d+/
+      )
+    })
+  }
+})