Unverified Commit ce207309 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[test] Add coverage for throwing custom "use cache" cache handler (#95984)

This is relevant if the cache is in a broken state or the keys or
entries are not suitable (e.g. an entry that's to large to be stored).

Revealed several oddities:
1. cache handler have no no sources content (not too bad since that
means the codeframe points into the problem `use cache` function which
is usually the cause)
2. A throwing `set` is swallowed in dev
3. A throwing `get` is logged as a caught error and an unhandled
rejection. This is spammy.
parent 13dad0dd
...@@ -114,6 +114,7 @@ ...@@ -114,6 +114,7 @@
"test/e2e/app-dir/app-client-cache/client-cache.parallel-routes.test.ts", "test/e2e/app-dir/app-client-cache/client-cache.parallel-routes.test.ts",
"test/e2e/app-dir/app-compilation/index.test.ts", "test/e2e/app-dir/app-compilation/index.test.ts",
"test/e2e/app-dir/app-css/index.test.ts", "test/e2e/app-dir/app-css/index.test.ts",
"test/e2e/app-dir/app-custom-cache-handler-errors/**/*",
"test/e2e/app-dir/app-custom-cache-handler/index.test.ts", "test/e2e/app-dir/app-custom-cache-handler/index.test.ts",
"test/e2e/app-dir/app-edge-root-layout/index.test.ts", "test/e2e/app-dir/app-edge-root-layout/index.test.ts",
"test/e2e/app-dir/app-edge/app-edge.test.ts", "test/e2e/app-dir/app-edge/app-edge.test.ts",
......
import { nextTestSetup } from 'e2e-utils'
import { hasErrorToast, retry, waitForNoRedbox } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
describe('app-custom-cache-handler-errors - get throws', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
env: { CACHE_HANDLER_THROW_ON: 'get' },
})
if (skipped) {
return
}
it('surfaces the cache handler error', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/?input=x')
if (isNextDev) {
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "CustomCacheHandler.get failed",
"environmentLabel": "Prefetch",
"label": "Runtime Error",
"source": "app/page.tsx (19:14) @ CachedData
> 19 | return <p>{await getCachedData(input)}</p>
| ^",
"stack": [
"Object.get throwing-cache-handler.js (24:13)",
"CachedData app/page.tsx (19:14)",
],
}
`)
} else {
// TODO(veil): Webpack renders the cache handler frame as a file://
// URL, which the redbox matcher flags as unintended.
await expect(browser).toDisplayRedbox(`
{
"description": "CustomCacheHandler.get failed",
"environmentLabel": "Prefetch",
"label": "Runtime Error",
"source": "app/page.tsx (19:14) @ CachedData
> 19 | return <p>{await getCachedData(input)}</p>
| ^",
"stack": [
"<FIXME-file-protocol>",
"CachedData app/page.tsx (19:14)",
],
}
`)
}
}
await retry(async () => {
expect(next.cliOutput.slice(outputIndex)).toContain('unhandledRejection:')
})
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
if (isNextDev) {
const errorBlock =
'Error: CustomCacheHandler.get failed' +
'\n at Object.get (throwing-cache-handler.js:24:13)' +
'\n at async CachedData (app/page.tsx:19:14)' +
"\n 17 | const { input = 'default' } = await searchParams" +
'\n 18 |' +
'\n> 19 | return <p>{await getCachedData(input)}</p>' +
'\n | ^' +
'\n 20 | }' +
'\n 21 |' +
'\n 22 | export default function Page({ {' +
"\n digest: '"
expect(cliOutput).toContain('⨯ ' + errorBlock)
// The same error is additionally reported as two unhandled rejections.
expect(cliOutput).toContain('⨯ unhandledRejection: ' + errorBlock)
expect(cliOutput).toContain('⨯ unhandledRejection: ' + errorBlock)
} else {
// In production, the frames below the cache handler frame are bundled
// code, and are therefore not stable across bundlers and builds.
const errorBlock =
'Error: CustomCacheHandler.get failed' +
'\n at Object.get (throwing-cache-handler.js:24:13)' +
'\n at '
expect(cliOutput).toContain('⨯ ' + errorBlock)
expect(cliOutput).toContain(" digest: '")
// The same error is additionally reported as an unhandled rejection.
expect(cliOutput).toContain('⨯ unhandledRejection: ' + errorBlock)
}
})
})
describe('app-custom-cache-handler-errors - set throws', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
env: { CACHE_HANDLER_THROW_ON: 'set' },
})
if (skipped) {
return
}
it('renders the page successfully', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/?input=x')
expect(await browser.elementByCss('p').text()).toBe(
'cached data for input: x'
)
if (isNextDev) {
// A throwing set() is currently completely silent in dev: the cache
// handler is called and its rejection is swallowed without being logged
// or reported to the dev overlay.
await waitForNoRedbox(browser)
expect(await hasErrorToast(browser)).toBe(false)
expect(next.cliOutput.slice(outputIndex)).not.toContain(
'CustomCacheHandler.set failed'
)
} else {
await retry(async () => {
expect(stripAnsi(next.cliOutput.slice(outputIndex))).toContain(
'Error: CustomCacheHandler.set failed' +
'\n at Object.set (throwing-cache-handler.js:50:13)' +
'\n at <unknown> ('
)
})
}
})
})
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
async function getCachedData(input: string) {
'use cache'
return `cached data for input: ${input}`
}
async function CachedData({
searchParams,
}: {
searchParams: Promise<{ input?: string }>
}) {
// Reading `searchParams` and passing the value into the cached function
// ensures that the cache handler is only invoked at request time, and not
// during build-time prerendering.
const { input = 'default' } = await searchParams
return <p>{await getCachedData(input)}</p>
}
export default function Page({
searchParams,
}: {
searchParams: Promise<{ input?: string }>
}) {
return (
<Suspense fallback={null}>
<CachedData searchParams={searchParams} />
</Suspense>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
cacheHandlers: {
default: require.resolve('./throwing-cache-handler.js'),
},
}
module.exports = nextConfig
// @ts-check
/**
* A self-contained "use cache" cache handler that throws from the method
* specified via the `CACHE_HANDLER_THROW_ON` env var ('get' or 'set'). The
* other methods behave like a normal in-memory cache so that the throwing
* method is actually reached.
*/
/**
* @typedef {import('next/dist/server/lib/cache-handlers/types').CacheEntry} CacheEntry
* @typedef {Omit<CacheEntry, 'value'> & { chunks: Uint8Array[] }} StoredEntry
*/
/** @type {Map<string, StoredEntry>} */
const cache = new Map()
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const cacheHandler = {
async get(cacheKey) {
if (process.env.CACHE_HANDLER_THROW_ON === 'get') {
throw new Error('CustomCacheHandler.get failed')
}
const storedEntry = cache.get(cacheKey)
if (storedEntry === undefined) {
return undefined
}
const { chunks, ...entry } = storedEntry
return {
...entry,
value: new ReadableStream({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(chunk)
}
controller.close()
},
}),
}
},
async set(cacheKey, pendingEntry) {
if (process.env.CACHE_HANDLER_THROW_ON === 'set') {
throw new Error('CustomCacheHandler.set failed')
}
const { value, ...entry } = await pendingEntry
/** @type {Uint8Array[]} */
const chunks = []
const reader = value.getReader()
while (true) {
const { done, value: chunk } = await reader.read()
if (done) {
break
}
chunks.push(chunk)
}
cache.set(cacheKey, { ...entry, chunks })
},
async refreshTags() {},
async getExpiration() {
return Infinity
},
async updateTags() {},
}
module.exports = cacheHandler
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